From 6ddcccb982369f20a3bec445cb5bb86721026793 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Wed, 7 Nov 2018 17:43:57 +0800 Subject: [PATCH 01/10] module change --- .../mquery/node_modules => }/bluebird/LICENSE | 6 +- .../node_modules => }/bluebird/README.md | 168 +- node_modules/bluebird/changelog.md | 1723 ++++++ node_modules/bluebird/js/browser/bluebird.js | 4887 +++++++++++++++++ .../bluebird/js/browser/bluebird.min.js | 31 + node_modules/bluebird/js/main/any.js | 21 + .../bluebird/js/main/assert.js | 26 - node_modules/bluebird/js/main/async.js | 150 + node_modules/bluebird/js/main/bind.js | 72 + node_modules/bluebird/js/main/bluebird.js | 11 + node_modules/bluebird/js/main/call_get.js | 123 + node_modules/bluebird/js/main/cancel.js | 48 + .../bluebird/js/main/captured_trace.js | 493 ++ node_modules/bluebird/js/main/catch_filter.js | 66 + node_modules/bluebird/js/main/context.js | 38 + .../bluebird/js/main/debuggability.js | 162 + .../bluebird/js/main/direct_resolve.js | 63 + node_modules/bluebird/js/main/each.js | 12 + .../bluebird/js/main/errors.js | 80 +- node_modules/bluebird/js/main/es5.js | 80 + node_modules/bluebird/js/main/filter.js | 12 + node_modules/bluebird/js/main/finally.js | 98 + node_modules/bluebird/js/main/generators.js | 136 + node_modules/bluebird/js/main/join.js | 107 + .../js/zalgo => bluebird/js/main}/map.js | 82 +- node_modules/bluebird/js/main/method.js | 44 + node_modules/bluebird/js/main/nodeify.js | 59 + node_modules/bluebird/js/main/progress.js | 76 + node_modules/bluebird/js/main/promise.js | 754 +++ .../bluebird/js/main/promise_array.js | 142 + .../bluebird/js/main/promise_resolver.js | 123 + .../bluebird/js/main/promisify.js | 245 +- node_modules/bluebird/js/main/props.js | 79 + node_modules/bluebird/js/main/queue.js | 90 + node_modules/bluebird/js/main/race.js | 47 + node_modules/bluebird/js/main/reduce.js | 148 + node_modules/bluebird/js/main/schedule.js | 35 + node_modules/bluebird/js/main/settle.js | 40 + node_modules/bluebird/js/main/some.js | 125 + .../js/main/synchronous_inspection.js | 94 + node_modules/bluebird/js/main/thenables.js | 84 + node_modules/bluebird/js/main/timers.js | 64 + .../js/zalgo => bluebird/js/main}/using.js | 123 +- node_modules/bluebird/js/main/util.js | 321 ++ node_modules/bluebird/package.json | 103 + .../node_modules => }/bson/.travis.yml | 0 .../mongodb/node_modules => }/bson/HISTORY | 4 + .../node_modules/mongodb => bson}/LICENSE | 0 .../mongodb/node_modules => }/bson/Makefile | 0 .../mongodb/node_modules => }/bson/README.md | 0 .../node_modules => }/bson/binding.gyp | 0 .../bson/browser_build/bson.js | 0 .../bson/browser_build/package.json | 0 .../node_modules => }/bson/build_browser.js | 0 node_modules/bson/builderror.log | 12 + .../node_modules => }/bson/ext/Makefile | 0 .../node_modules => }/bson/ext/bson.cc | 0 .../mongodb/node_modules => }/bson/ext/bson.h | 0 .../node_modules => }/bson/ext/index.js | 10 +- .../bson/ext/win32/ia32/bson.node | Bin .../bson/ext/win32/x64/bson.node | Bin .../node_modules => }/bson/ext/wscript | 0 .../node_modules => }/bson/lib/bson/binary.js | 0 .../bson/lib/bson/binary_parser.js | 0 .../node_modules => }/bson/lib/bson/bson.js | 0 .../bson/lib/bson/bson_new.js | 0 .../node_modules => }/bson/lib/bson/code.js | 0 .../node_modules => }/bson/lib/bson/db_ref.js | 0 .../node_modules => }/bson/lib/bson/double.js | 0 .../bson/lib/bson/float_parser.js | 0 .../node_modules => }/bson/lib/bson/index.js | 0 .../node_modules => }/bson/lib/bson/long.js | 0 .../bson/lib/bson/max_key.js | 0 .../bson/lib/bson/min_key.js | 0 .../bson/lib/bson/objectid.js | 0 .../node_modules => }/bson/lib/bson/symbol.js | 0 .../bson/lib/bson/timestamp.js | 0 .../node_modules => }/bson/package.json | 94 +- .../node_modules => }/bson/tools/gleak.js | 0 .../bson/tools/jasmine-1.1.0/MIT.LICENSE | 0 .../bson/tools/jasmine-1.1.0/jasmine-html.js | 0 .../bson/tools/jasmine-1.1.0/jasmine.css | 0 .../bson/tools/jasmine-1.1.0/jasmine.js | 0 .../tools/jasmine-1.1.0/jasmine_favicon.png | Bin node_modules/debug/.jshintrc | 3 + node_modules/debug/.npmignore | 6 + node_modules/debug/History.md | 195 + node_modules/debug/Makefile | 36 + .../mquery/node_modules => }/debug/Readme.md | 99 +- node_modules/debug/bower.json | 28 + node_modules/debug/browser.js | 168 + node_modules/debug/component.json | 19 + node_modules/debug/debug.js | 197 + node_modules/debug/node.js | 209 + node_modules/debug/node_modules/ms/.npmignore | 5 + node_modules/debug/node_modules/ms/History.md | 66 + node_modules/debug/node_modules/ms/LICENSE | 20 + node_modules/debug/node_modules/ms/README.md | 35 + node_modules/debug/node_modules/ms/index.js | 125 + .../debug/node_modules/ms/package.json | 49 + node_modules/debug/package.json | 70 + .../node_modules => }/hooks/.npmignore | 0 .../node_modules => }/hooks/Makefile | 0 .../node_modules => }/hooks/README.md | 0 .../node_modules => }/hooks/hooks.alt.js | 0 .../node_modules => }/hooks/hooks.js | 0 node_modules/hooks/package.json | 88 + .../{mongoose/node_modules => }/hooks/test.js | 0 .../node_modules => }/inherits/LICENSE | 0 .../node_modules => }/inherits/README.md | 0 node_modules/inherits/inherits.js | 7 + .../inherits/inherits_browser.js | 0 node_modules/inherits/package.json | 61 + .../node_modules/bson => kerberos}/LICENSE | 0 .../node_modules => }/kerberos/README.md | 0 .../node_modules => }/kerberos/binding.gyp | 0 node_modules/kerberos/builderror.log | 12 + .../node_modules => }/kerberos/index.js | 0 .../kerberos/lib/auth_processes/mongodb.js | 0 .../node_modules => }/kerberos/lib/base64.c | 0 .../node_modules => }/kerberos/lib/base64.h | 0 .../kerberos/lib/kerberos.cc | 0 .../node_modules => }/kerberos/lib/kerberos.h | 0 .../kerberos/lib/kerberos.js | 0 .../kerberos/lib/kerberos_context.cc | 0 .../kerberos/lib/kerberos_context.h | 0 .../kerberos/lib/kerberosgss.c | 0 .../kerberos/lib/kerberosgss.h | 0 .../node_modules => }/kerberos/lib/sspi.js | 0 .../kerberos/lib/win32/base64.c | 0 .../kerberos/lib/win32/base64.h | 0 .../kerberos/lib/win32/kerberos.cc | 0 .../kerberos/lib/win32/kerberos.h | 0 .../kerberos/lib/win32/kerberos_sspi.c | 0 .../kerberos/lib/win32/kerberos_sspi.h | 0 .../kerberos/lib/win32/worker.cc | 0 .../kerberos/lib/win32/worker.h | 0 .../lib/win32/wrappers/security_buffer.cc | 0 .../lib/win32/wrappers/security_buffer.h | 0 .../lib/win32/wrappers/security_buffer.js | 0 .../wrappers/security_buffer_descriptor.cc | 0 .../wrappers/security_buffer_descriptor.h | 0 .../wrappers/security_buffer_descriptor.js | 0 .../lib/win32/wrappers/security_context.cc | 0 .../lib/win32/wrappers/security_context.h | 0 .../lib/win32/wrappers/security_context.js | 0 .../win32/wrappers/security_credentials.cc | 0 .../lib/win32/wrappers/security_credentials.h | 0 .../win32/wrappers/security_credentials.js | 0 .../node_modules => }/kerberos/lib/worker.cc | 0 .../node_modules => }/kerberos/lib/worker.h | 0 node_modules/kerberos/package.json | 59 + .../kerberos/test/kerberos_tests.js | 0 .../kerberos/test/kerberos_win32_test.js | 0 .../win32/security_buffer_descriptor_tests.js | 0 .../test/win32/security_buffer_tests.js | 0 .../test/win32/security_credentials_tests.js | 0 .../node_modules => }/mongodb/.gitmodules | 0 .../node_modules => }/mongodb/.travis.yml | 0 .../node_modules => }/mongodb/CONTRIBUTING.md | 0 node_modules/mongodb/HISTORY | 1052 ++++ .../node_modules/kerberos => mongodb}/LICENSE | 0 .../node_modules => }/mongodb/Makefile | 0 .../node_modules => }/mongodb/Readme.md | 0 .../node_modules => }/mongodb/index.js | 0 .../mongodb/lib/mongodb/admin.js | 0 .../mongodb/lib/mongodb/aggregation_cursor.js | 0 .../mongodb/lib/mongodb/auth/mongodb_cr.js | 0 .../lib/mongodb/auth/mongodb_gssapi.js | 0 .../mongodb/lib/mongodb/auth/mongodb_plain.js | 0 .../mongodb/lib/mongodb/auth/mongodb_scram.js | 44 +- .../mongodb/lib/mongodb/auth/mongodb_sspi.js | 0 .../mongodb/lib/mongodb/auth/mongodb_x509.js | 0 .../mongodb/lib/mongodb/collection.js | 0 .../lib/mongodb/collection/aggregation.js | 0 .../lib/mongodb/collection/batch/common.js | 1 + .../lib/mongodb/collection/batch/ordered.js | 0 .../lib/mongodb/collection/batch/unordered.js | 31 +- .../lib/mongodb/collection/commands.js | 0 .../mongodb/lib/mongodb/collection/core.js | 0 .../mongodb/lib/mongodb/collection/geo.js | 0 .../mongodb/lib/mongodb/collection/index.js | 0 .../mongodb/lib/mongodb/collection/query.js | 0 .../mongodb/lib/mongodb/collection/shared.js | 0 .../mongodb/lib/mongodb/command_cursor.js | 0 .../lib/mongodb/commands/base_command.js | 0 .../lib/mongodb/commands/db_command.js | 0 .../lib/mongodb/commands/delete_command.js | 0 .../lib/mongodb/commands/get_more_command.js | 0 .../lib/mongodb/commands/insert_command.js | 0 .../mongodb/commands/kill_cursor_command.js | 0 .../lib/mongodb/commands/query_command.js | 0 .../lib/mongodb/commands/update_command.js | 0 .../mongodb/lib/mongodb/connection/base.js | 0 .../lib/mongodb/connection/connection.js | 0 .../lib/mongodb/connection/connection_pool.js | 0 .../mongodb/connection/connection_utils.js | 0 .../mongodb/lib/mongodb/connection/mongos.js | 0 .../lib/mongodb/connection/read_preference.js | 0 .../lib/mongodb/connection/repl_set/ha.js | 0 .../mongodb/connection/repl_set/options.js | 0 .../mongodb/connection/repl_set/repl_set.js | 0 .../connection/repl_set/repl_set_state.js | 0 .../repl_set/strategies/ping_strategy.js | 0 .../strategies/statistics_strategy.js | 0 .../mongodb/lib/mongodb/connection/server.js | 1 + .../mongodb/connection/server_capabilities.js | 0 .../lib/mongodb/connection/url_parser.js | 0 .../mongodb/lib/mongodb/cursor.js | 0 .../mongodb/lib/mongodb/cursorstream.js | 0 .../mongodb/lib/mongodb/db.js | 4 +- .../mongodb/lib/mongodb/gridfs/chunk.js | 0 .../mongodb/lib/mongodb/gridfs/grid.js | 0 .../mongodb/lib/mongodb/gridfs/gridstore.js | 32 +- .../mongodb/lib/mongodb/gridfs/readstream.js | 0 .../mongodb/lib/mongodb/index.js | 0 .../mongodb/lib/mongodb/mongo_client.js | 0 .../lib/mongodb/responses/mongo_reply.js | 0 .../mongodb/lib/mongodb/scope.js | 0 .../mongodb/lib/mongodb/utils.js | 0 .../node_modules => }/mongodb/package.json | 111 +- node_modules/mongodb/repo_node_418.js | 33 + node_modules/mongodb/wercker.yml | 17 + node_modules/mongoose/.travis.yml | 4 +- node_modules/mongoose/History.md | 44 + node_modules/mongoose/bin/mongoose.min.js | 16 +- node_modules/mongoose/lib/aggregate.js | 7 +- node_modules/mongoose/lib/document.js | 7 +- node_modules/mongoose/lib/query.js | 22 +- node_modules/mongoose/lib/schema.js | 7 +- node_modules/mongoose/lib/schema/buffer.js | 3 + .../mongoose/lib/schema/documentarray.js | 1 - node_modules/mongoose/lib/schema/string.js | 12 +- node_modules/mongoose/lib/schematype.js | 16 +- node_modules/mongoose/lib/types/array.js | 6 + node_modules/mongoose/lib/utils.js | 1 - .../mongoose/node_modules/hooks/package.json | 65 - .../nan/nan_implementation_pre_12_inl.h | 268 - .../bson/node_modules/nan/package.json | 89 - .../kerberos/node_modules/nan/.dntrc | 30 - .../kerberos/node_modules/nan/CHANGELOG.md | 265 - .../kerberos/node_modules/nan/LICENSE.md | 13 - .../kerberos/node_modules/nan/appveyor.yml | 37 - .../kerberos/node_modules/nan/include_dirs.js | 1 - .../kerberos/node_modules/nan/nan.h | 2174 -------- .../nan/nan_implementation_12_inl.h | 262 - .../kerberos/node_modules/nan/nan_new.h | 329 -- .../node_modules/nan/nan_string_bytes.h | 312 -- .../node_modules/kerberos/package.json | 55 - .../node_modules/readable-stream/.npmignore | 5 - .../node_modules/readable-stream/README.md | 15 - .../node_modules/readable-stream/duplex.js | 1 - .../readable-stream/lib/_stream_duplex.js | 89 - .../readable-stream/lib/_stream_readable.js | 982 ---- .../readable-stream/lib/_stream_writable.js | 386 -- .../node_modules/core-util-is/README.md | 3 - .../node_modules/core-util-is/float.patch | 604 -- .../node_modules/core-util-is/lib/util.js | 107 - .../node_modules/core-util-is/package.json | 53 - .../node_modules/core-util-is/util.js | 106 - .../node_modules/inherits/inherits.js | 1 - .../node_modules/inherits/package.json | 50 - .../node_modules/inherits/test.js | 25 - .../node_modules/isarray/README.md | 54 - .../node_modules/isarray/build/build.js | 209 - .../node_modules/isarray/component.json | 19 - .../node_modules/isarray/index.js | 3 - .../node_modules/isarray/package.json | 53 - .../node_modules/string_decoder/.npmignore | 2 - .../node_modules/string_decoder/LICENSE | 20 - .../node_modules/string_decoder/README.md | 7 - .../node_modules/string_decoder/index.js | 221 - .../node_modules/string_decoder/package.json | 54 - .../node_modules/readable-stream/package.json | 70 - .../readable-stream/passthrough.js | 1 - .../node_modules/readable-stream/transform.js | 1 - .../node_modules/readable-stream/writable.js | 1 - .../node_modules/bluebird/js/main/any.js | 46 - .../node_modules/bluebird/js/main/async.js | 111 - .../node_modules/bluebird/js/main/bluebird.js | 25 - .../node_modules/bluebird/js/main/call_get.js | 119 - .../node_modules/bluebird/js/main/cancel.js | 75 - .../bluebird/js/main/captured_trace.js | 233 - .../bluebird/js/main/catch_filter.js | 94 - .../bluebird/js/main/direct_resolve.js | 78 - .../node_modules/bluebird/js/main/each.js | 34 - .../bluebird/js/main/errors_api_rejection.js | 38 - .../node_modules/bluebird/js/main/es5.js | 87 - .../node_modules/bluebird/js/main/filter.js | 34 - .../node_modules/bluebird/js/main/finally.js | 120 - .../bluebird/js/main/generators.js | 151 - .../node_modules/bluebird/js/main/join.js | 122 - .../node_modules/bluebird/js/main/map.js | 149 - .../node_modules/bluebird/js/main/nodeify.js | 76 - .../node_modules/bluebird/js/main/progress.js | 112 - .../node_modules/bluebird/js/main/promise.js | 1077 ---- .../bluebird/js/main/promise_array.js | 202 - .../bluebird/js/main/promise_resolver.js | 158 - .../node_modules/bluebird/js/main/props.js | 108 - .../node_modules/bluebird/js/main/queue.js | 115 - .../node_modules/bluebird/js/main/race.js | 72 - .../node_modules/bluebird/js/main/reduce.js | 181 - .../node_modules/bluebird/js/main/schedule.js | 61 - .../node_modules/bluebird/js/main/settle.js | 67 - .../node_modules/bluebird/js/main/some.js | 161 - .../js/main/synchronous_inspection.js | 76 - .../bluebird/js/main/thenables.js | 133 - .../node_modules/bluebird/js/main/timers.js | 91 - .../node_modules/bluebird/js/main/using.js | 190 - .../node_modules/bluebird/js/main/util.js | 268 - .../node_modules/bluebird/js/zalgo/any.js | 46 - .../node_modules/bluebird/js/zalgo/assert.js | 81 - .../node_modules/bluebird/js/zalgo/async.js | 111 - .../bluebird/js/zalgo/bluebird.js | 25 - .../bluebird/js/zalgo/call_get.js | 119 - .../node_modules/bluebird/js/zalgo/cancel.js | 75 - .../bluebird/js/zalgo/captured_trace.js | 233 - .../bluebird/js/zalgo/catch_filter.js | 94 - .../bluebird/js/zalgo/direct_resolve.js | 78 - .../node_modules/bluebird/js/zalgo/each.js | 34 - .../node_modules/bluebird/js/zalgo/errors.js | 145 - .../bluebird/js/zalgo/errors_api_rejection.js | 38 - .../node_modules/bluebird/js/zalgo/es5.js | 87 - .../node_modules/bluebird/js/zalgo/filter.js | 34 - .../node_modules/bluebird/js/zalgo/finally.js | 120 - .../bluebird/js/zalgo/generators.js | 151 - .../node_modules/bluebird/js/zalgo/join.js | 122 - .../node_modules/bluebird/js/zalgo/nodeify.js | 76 - .../bluebird/js/zalgo/progress.js | 110 - .../node_modules/bluebird/js/zalgo/promise.js | 1077 ---- .../bluebird/js/zalgo/promise_array.js | 202 - .../bluebird/js/zalgo/promise_resolver.js | 158 - .../bluebird/js/zalgo/promisify.js | 326 -- .../node_modules/bluebird/js/zalgo/props.js | 108 - .../node_modules/bluebird/js/zalgo/queue.js | 115 - .../node_modules/bluebird/js/zalgo/race.js | 72 - .../node_modules/bluebird/js/zalgo/reduce.js | 181 - .../bluebird/js/zalgo/schedule.js | 61 - .../node_modules/bluebird/js/zalgo/settle.js | 67 - .../node_modules/bluebird/js/zalgo/some.js | 161 - .../js/zalgo/synchronous_inspection.js | 76 - .../bluebird/js/zalgo/thenables.js | 133 - .../node_modules/bluebird/js/zalgo/timers.js | 91 - .../node_modules/bluebird/js/zalgo/util.js | 268 - .../mquery/node_modules/bluebird/package.json | 92 - .../mquery/node_modules/bluebird/zalgo.js | 1 - .../mquery/node_modules/debug/debug.js | 137 - .../mquery/node_modules/debug/index.js | 5 - .../mquery/node_modules/debug/lib/debug.js | 147 - .../mquery/node_modules/debug/package.json | 63 - .../mongoose/node_modules/mquery/package.json | 67 - .../mongoose/node_modules/sliced/package.json | 48 - node_modules/mongoose/package.json | 139 +- .../node_modules => }/mpath/.npmignore | 0 .../node_modules => }/mpath/.travis.yml | 0 .../node_modules => }/mpath/History.md | 0 .../{mongoose/node_modules => }/mpath/LICENSE | 0 .../node_modules => }/mpath/Makefile | 0 .../node_modules => }/mpath/README.md | 0 .../node_modules => }/mpath/index.js | 0 .../node_modules => }/mpath/lib/index.js | 0 .../node_modules => }/mpath/package.json | 75 +- .../node_modules => }/mpath/test/index.js | 0 .../node_modules => }/mpromise/.idea/.name | 0 .../mpromise/.idea/codeStyleSettings.xml | 0 .../mpromise/.idea/encodings.xml | 0 .../inspectionProfiles/Project_Default.xml | 0 .../inspectionProfiles/profiles_settings.xml | 0 .../mpromise/.idea/jsLibraryMappings.xml | 0 .../Node_js_Dependencies_for_mpromise.xml | 0 .../node_modules => }/mpromise/.idea/misc.xml | 0 .../mpromise/.idea/modules.xml | 0 .../mpromise/.idea/mpromise.iml | 0 .../mpromise/.idea/other.xml | 0 .../mpromise/.idea/scopes/scope_settings.xml | 0 .../node_modules => }/mpromise/.idea/vcs.xml | 0 .../mpromise/.idea/workspace.xml | 0 .../node_modules => }/mpromise/.npmignore | 0 .../node_modules => }/mpromise/.travis.yml | 0 .../node_modules => }/mpromise/History.md | 0 .../node_modules => }/mpromise/LICENSE | 0 .../node_modules => }/mpromise/README.md | 0 .../node_modules => }/mpromise/index.js | 0 .../node_modules => }/mpromise/lib/promise.js | 0 .../node_modules => }/mpromise/package.json | 85 +- .../mpromise/test/promise.domain.test.js | 0 .../mpromise/test/promise.test.js | 0 .../mpromise/test/promises.Aplus.js | 0 .../node_modules => }/mquery/.npmignore | 0 .../node_modules => }/mquery/.travis.yml | 7 +- .../node_modules => }/mquery/History.md | 49 +- .../node_modules => }/mquery/LICENSE | 0 .../node_modules => }/mquery/Makefile | 0 .../node_modules => }/mquery/README.md | 0 .../mquery/lib/collection/collection.js | 0 .../mquery/lib/collection/index.js | 0 .../mquery/lib/collection/node.js | 8 + .../node_modules => }/mquery/lib/env.js | 0 node_modules/mquery/lib/helper.js | 30 + .../node_modules => }/mquery/lib/mquery.js | 152 +- .../mquery/lib/permissions.js | 3 - .../node_modules => }/mquery/lib/utils.js | 11 + node_modules/mquery/package.json | 63 + .../mquery/test/collection/browser.js | 0 .../mquery/test/collection/mongo.js | 0 .../mquery/test/collection/node.js | 0 .../node_modules => }/mquery/test/env.js | 0 .../node_modules => }/mquery/test/index.js | 74 +- .../mquery/test/utils.test.js | 0 .../{mongoose/node_modules => }/ms/.npmignore | 0 .../{mongoose/node_modules => }/ms/Makefile | 0 .../{mongoose/node_modules => }/ms/README.md | 0 .../{mongoose/node_modules => }/ms/ms.js | 0 .../node_modules => }/ms/package.json | 61 +- .../node_modules => }/ms/test/index.html | 0 .../ms/test/support/jquery.js | 0 .../node_modules => }/ms/test/test.js | 0 .../node_modules => }/muri/.npmignore | 0 .../node_modules => }/muri/.travis.yml | 0 .../node_modules => }/muri/History.md | 0 .../{mongoose/node_modules => }/muri/LICENSE | 0 .../{mongoose/node_modules => }/muri/Makefile | 0 .../node_modules => }/muri/README.md | 0 .../{mongoose/node_modules => }/muri/index.js | 0 .../node_modules => }/muri/lib/index.js | 0 .../node_modules => }/muri/package.json | 83 +- .../node_modules => }/muri/test/index.js | 0 .../bson/node_modules => }/nan/.dntrc | 0 .../bson/node_modules => }/nan/CHANGELOG.md | 26 +- .../bson/node_modules => }/nan/LICENSE.md | 0 node_modules/nan/README.md | 1402 +++++ .../bson/node_modules => }/nan/appveyor.yml | 0 .../node_modules => }/nan/include_dirs.js | 0 .../bson/node_modules => }/nan/nan.h | 126 +- .../nan/nan_implementation_12_inl.h | 9 +- .../nan/nan_implementation_pre_12_inl.h | 9 +- .../bson/node_modules => }/nan/nan_new.h | 7 +- .../node_modules => }/nan/nan_string_bytes.h | 0 .../node_modules => }/nan/package.json | 77 +- node_modules/readable-stream/.airtap.yml | 17 + node_modules/readable-stream/.airtaprc | 2 + node_modules/readable-stream/.travis.yml | 22 + node_modules/readable-stream/CONTRIBUTING.md | 38 + node_modules/readable-stream/GOVERNANCE.md | 136 + node_modules/readable-stream/LICENSE | 47 + node_modules/readable-stream/README.md | 111 + .../readable-stream/errors-browser.js | 131 + node_modules/readable-stream/errors.js | 116 + .../readable-stream/experimentalWarning.js | 17 + .../readable-stream/lib/_stream_duplex.js | 141 + .../lib/_stream_passthrough.js | 16 +- .../readable-stream/lib/_stream_readable.js | 1047 ++++ .../readable-stream/lib/_stream_transform.js | 136 +- .../readable-stream/lib/_stream_writable.js | 701 +++ .../lib/internal/streams/async_iterator.js | 174 + .../lib/internal/streams/buffer_list.js | 163 + .../lib/internal/streams/destroy.js | 86 + .../lib/internal/streams/end-of-stream.js | 94 + .../lib/internal/streams/pipeline.js | 99 + .../lib/internal/streams/state.js | 25 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + node_modules/readable-stream/package.json | 109 + .../readable-browser.js} | 3 +- node_modules/readable-stream/readable.js | 21 + .../node_modules => }/regexp-clone/.npmignore | 0 .../regexp-clone/.travis.yml | 0 .../node_modules => }/regexp-clone/History.md | 0 .../node_modules => }/regexp-clone/LICENSE | 0 .../node_modules => }/regexp-clone/Makefile | 0 .../node_modules => }/regexp-clone/README.md | 0 .../node_modules => }/regexp-clone/index.js | 0 .../regexp-clone/package.json | 74 +- .../regexp-clone/test/index.js | 0 .../readable-stream => safe-buffer}/LICENSE | 19 +- node_modules/safe-buffer/README.md | 584 ++ node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 62 + node_modules/safe-buffer/package.json | 62 + .../node_modules => }/sliced/.npmignore | 0 .../node_modules => }/sliced/.travis.yml | 0 .../node_modules => }/sliced/History.md | 0 .../node_modules => }/sliced/LICENSE | 0 .../node_modules => }/sliced/Makefile | 0 .../node_modules => }/sliced/README.md | 0 .../node_modules => }/sliced/bench.js | 0 .../node_modules => }/sliced/component.json | 0 .../node_modules => }/sliced/index.js | 0 .../node_modules => }/sliced/lib/sliced.js | 0 node_modules/sliced/package.json | 73 + .../node_modules => }/sliced/test/index.js | 0 node_modules/string_decoder/.travis.yml | 50 + node_modules/string_decoder/LICENSE | 48 + node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 296 + node_modules/string_decoder/package.json | 59 + node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 56 + package-lock.json | 543 ++ 503 files changed, 21896 insertions(+), 18161 deletions(-) rename node_modules/{mongoose/node_modules/mquery/node_modules => }/bluebird/LICENSE (89%) rename node_modules/{mongoose/node_modules/mquery/node_modules => }/bluebird/README.md (78%) create mode 100644 node_modules/bluebird/changelog.md create mode 100644 node_modules/bluebird/js/browser/bluebird.js create mode 100644 node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 node_modules/bluebird/js/main/any.js rename node_modules/{mongoose/node_modules/mquery/node_modules => }/bluebird/js/main/assert.js (57%) create mode 100644 node_modules/bluebird/js/main/async.js create mode 100644 node_modules/bluebird/js/main/bind.js create mode 100644 node_modules/bluebird/js/main/bluebird.js create mode 100644 node_modules/bluebird/js/main/call_get.js create mode 100644 node_modules/bluebird/js/main/cancel.js create mode 100644 node_modules/bluebird/js/main/captured_trace.js create mode 100644 node_modules/bluebird/js/main/catch_filter.js create mode 100644 node_modules/bluebird/js/main/context.js create mode 100644 node_modules/bluebird/js/main/debuggability.js create mode 100644 node_modules/bluebird/js/main/direct_resolve.js create mode 100644 node_modules/bluebird/js/main/each.js rename node_modules/{mongoose/node_modules/mquery/node_modules => }/bluebird/js/main/errors.js (55%) create mode 100644 node_modules/bluebird/js/main/es5.js create mode 100644 node_modules/bluebird/js/main/filter.js create mode 100644 node_modules/bluebird/js/main/finally.js create mode 100644 node_modules/bluebird/js/main/generators.js create mode 100644 node_modules/bluebird/js/main/join.js rename node_modules/{mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo => bluebird/js/main}/map.js (53%) create mode 100644 node_modules/bluebird/js/main/method.js create mode 100644 node_modules/bluebird/js/main/nodeify.js create mode 100644 node_modules/bluebird/js/main/progress.js create mode 100644 node_modules/bluebird/js/main/promise.js create mode 100644 node_modules/bluebird/js/main/promise_array.js create mode 100644 node_modules/bluebird/js/main/promise_resolver.js rename node_modules/{mongoose/node_modules/mquery/node_modules => }/bluebird/js/main/promisify.js (50%) create mode 100644 node_modules/bluebird/js/main/props.js create mode 100644 node_modules/bluebird/js/main/queue.js create mode 100644 node_modules/bluebird/js/main/race.js create mode 100644 node_modules/bluebird/js/main/reduce.js create mode 100644 node_modules/bluebird/js/main/schedule.js create mode 100644 node_modules/bluebird/js/main/settle.js create mode 100644 node_modules/bluebird/js/main/some.js create mode 100644 node_modules/bluebird/js/main/synchronous_inspection.js create mode 100644 node_modules/bluebird/js/main/thenables.js create mode 100644 node_modules/bluebird/js/main/timers.js rename node_modules/{mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo => bluebird/js/main}/using.js (58%) create mode 100644 node_modules/bluebird/js/main/util.js create mode 100644 node_modules/bluebird/package.json rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/.travis.yml (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/HISTORY (90%) rename node_modules/{mongoose/node_modules/mongodb => bson}/LICENSE (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/Makefile (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/README.md (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/binding.gyp (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/browser_build/bson.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/browser_build/package.json (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/build_browser.js (100%) create mode 100644 node_modules/bson/builderror.log rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/Makefile (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/bson.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/bson.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/index.js (88%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/win32/ia32/bson.node (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/win32/x64/bson.node (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/ext/wscript (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/binary.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/binary_parser.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/bson.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/bson_new.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/code.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/db_ref.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/double.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/float_parser.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/index.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/long.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/max_key.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/min_key.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/objectid.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/symbol.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/lib/bson/timestamp.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/package.json (57%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/gleak.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/jasmine-1.1.0/MIT.LICENSE (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/jasmine-1.1.0/jasmine-html.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/jasmine-1.1.0/jasmine.css (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/jasmine-1.1.0/jasmine.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/bson/tools/jasmine-1.1.0/jasmine_favicon.png (100%) create mode 100644 node_modules/debug/.jshintrc create mode 100644 node_modules/debug/.npmignore create mode 100644 node_modules/debug/History.md create mode 100644 node_modules/debug/Makefile rename node_modules/{mongoose/node_modules/mquery/node_modules => }/debug/Readme.md (58%) create mode 100644 node_modules/debug/bower.json create mode 100644 node_modules/debug/browser.js create mode 100644 node_modules/debug/component.json create mode 100644 node_modules/debug/debug.js create mode 100644 node_modules/debug/node.js create mode 100644 node_modules/debug/node_modules/ms/.npmignore create mode 100644 node_modules/debug/node_modules/ms/History.md create mode 100644 node_modules/debug/node_modules/ms/LICENSE create mode 100644 node_modules/debug/node_modules/ms/README.md create mode 100644 node_modules/debug/node_modules/ms/index.js create mode 100644 node_modules/debug/node_modules/ms/package.json create mode 100644 node_modules/debug/package.json rename node_modules/{mongoose/node_modules => }/hooks/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/hooks/Makefile (100%) rename node_modules/{mongoose/node_modules => }/hooks/README.md (100%) rename node_modules/{mongoose/node_modules => }/hooks/hooks.alt.js (100%) rename node_modules/{mongoose/node_modules => }/hooks/hooks.js (100%) create mode 100644 node_modules/hooks/package.json rename node_modules/{mongoose/node_modules => }/hooks/test.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules => }/inherits/LICENSE (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules => }/inherits/README.md (100%) create mode 100644 node_modules/inherits/inherits.js rename node_modules/{mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules => }/inherits/inherits_browser.js (100%) create mode 100644 node_modules/inherits/package.json rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson => kerberos}/LICENSE (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/README.md (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/binding.gyp (100%) create mode 100644 node_modules/kerberos/builderror.log rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/index.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/auth_processes/mongodb.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/base64.c (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/base64.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberos.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberos.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberos.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberos_context.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberos_context.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberosgss.c (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/kerberosgss.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/sspi.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/base64.c (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/base64.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/kerberos.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/kerberos.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/kerberos_sspi.c (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/kerberos_sspi.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/worker.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/worker.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer_descriptor.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_buffer_descriptor.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_context.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_context.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_context.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_credentials.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_credentials.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/win32/wrappers/security_credentials.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/worker.cc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/lib/worker.h (100%) create mode 100644 node_modules/kerberos/package.json rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/test/kerberos_tests.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/test/kerberos_win32_test.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/test/win32/security_buffer_descriptor_tests.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/test/win32/security_buffer_tests.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/kerberos/test/win32/security_credentials_tests.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/.gitmodules (100%) rename node_modules/{mongoose/node_modules => }/mongodb/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/mongodb/CONTRIBUTING.md (100%) create mode 100644 node_modules/mongodb/HISTORY rename node_modules/{mongoose/node_modules/mongodb/node_modules/kerberos => mongodb}/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/mongodb/Makefile (100%) rename node_modules/{mongoose/node_modules => }/mongodb/Readme.md (100%) rename node_modules/{mongoose/node_modules => }/mongodb/index.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/admin.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/aggregation_cursor.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_cr.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_gssapi.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_plain.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_scram.js (88%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_sspi.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/auth/mongodb_x509.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/aggregation.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/batch/common.js (99%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/batch/ordered.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/batch/unordered.js (94%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/commands.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/core.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/geo.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/index.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/query.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/collection/shared.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/command_cursor.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/base_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/db_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/delete_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/get_more_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/insert_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/kill_cursor_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/query_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/commands/update_command.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/base.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/connection.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/connection_pool.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/connection_utils.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/mongos.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/read_preference.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/ha.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/options.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/repl_set.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/server.js (99%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/server_capabilities.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/connection/url_parser.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/cursor.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/cursorstream.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/db.js (99%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/gridfs/chunk.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/gridfs/grid.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/gridfs/gridstore.js (98%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/gridfs/readstream.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/index.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/mongo_client.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/responses/mongo_reply.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/scope.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/lib/mongodb/utils.js (100%) rename node_modules/{mongoose/node_modules => }/mongodb/package.json (78%) create mode 100644 node_modules/mongodb/repo_node_418.js create mode 100644 node_modules/mongodb/wercker.yml delete mode 100644 node_modules/mongoose/node_modules/hooks/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors_api_rejection.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/schedule.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/any.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/assert.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/async.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/bluebird.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/call_get.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/cancel.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/captured_trace.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/catch_filter.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/direct_resolve.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/each.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors_api_rejection.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/es5.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/filter.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/finally.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/generators.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/join.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/nodeify.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/progress.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_array.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_resolver.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promisify.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/props.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/queue.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/race.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/reduce.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/schedule.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/settle.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/some.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/synchronous_inspection.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/thenables.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/timers.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/util.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/bluebird/zalgo.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js delete mode 100644 node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json delete mode 100644 node_modules/mongoose/node_modules/mquery/package.json delete mode 100644 node_modules/mongoose/node_modules/sliced/package.json rename node_modules/{mongoose/node_modules => }/mpath/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/mpath/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/mpath/History.md (100%) rename node_modules/{mongoose/node_modules => }/mpath/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/mpath/Makefile (100%) rename node_modules/{mongoose/node_modules => }/mpath/README.md (100%) rename node_modules/{mongoose/node_modules => }/mpath/index.js (100%) rename node_modules/{mongoose/node_modules => }/mpath/lib/index.js (100%) rename node_modules/{mongoose/node_modules => }/mpath/package.json (55%) rename node_modules/{mongoose/node_modules => }/mpath/test/index.js (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/.name (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/codeStyleSettings.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/encodings.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/inspectionProfiles/Project_Default.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/inspectionProfiles/profiles_settings.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/jsLibraryMappings.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/misc.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/modules.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/mpromise.iml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/other.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/scopes/scope_settings.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/vcs.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.idea/workspace.xml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/mpromise/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/mpromise/History.md (100%) rename node_modules/{mongoose/node_modules => }/mpromise/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/mpromise/README.md (100%) rename node_modules/{mongoose/node_modules => }/mpromise/index.js (100%) rename node_modules/{mongoose/node_modules => }/mpromise/lib/promise.js (100%) rename node_modules/{mongoose/node_modules => }/mpromise/package.json (64%) rename node_modules/{mongoose/node_modules => }/mpromise/test/promise.domain.test.js (100%) rename node_modules/{mongoose/node_modules => }/mpromise/test/promise.test.js (100%) rename node_modules/{mongoose/node_modules => }/mpromise/test/promises.Aplus.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/mquery/.travis.yml (56%) rename node_modules/{mongoose/node_modules => }/mquery/History.md (78%) rename node_modules/{mongoose/node_modules => }/mquery/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/mquery/Makefile (100%) rename node_modules/{mongoose/node_modules => }/mquery/README.md (100%) rename node_modules/{mongoose/node_modules => }/mquery/lib/collection/collection.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/lib/collection/index.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/lib/collection/node.js (92%) rename node_modules/{mongoose/node_modules => }/mquery/lib/env.js (100%) create mode 100644 node_modules/mquery/lib/helper.js rename node_modules/{mongoose/node_modules => }/mquery/lib/mquery.js (94%) rename node_modules/{mongoose/node_modules => }/mquery/lib/permissions.js (96%) rename node_modules/{mongoose/node_modules => }/mquery/lib/utils.js (97%) create mode 100644 node_modules/mquery/package.json rename node_modules/{mongoose/node_modules => }/mquery/test/collection/browser.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/test/collection/mongo.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/test/collection/node.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/test/env.js (100%) rename node_modules/{mongoose/node_modules => }/mquery/test/index.js (98%) rename node_modules/{mongoose/node_modules => }/mquery/test/utils.test.js (100%) rename node_modules/{mongoose/node_modules => }/ms/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/ms/Makefile (100%) rename node_modules/{mongoose/node_modules => }/ms/README.md (100%) rename node_modules/{mongoose/node_modules => }/ms/ms.js (100%) rename node_modules/{mongoose/node_modules => }/ms/package.json (54%) rename node_modules/{mongoose/node_modules => }/ms/test/index.html (100%) rename node_modules/{mongoose/node_modules => }/ms/test/support/jquery.js (100%) rename node_modules/{mongoose/node_modules => }/ms/test/test.js (100%) rename node_modules/{mongoose/node_modules => }/muri/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/muri/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/muri/History.md (100%) rename node_modules/{mongoose/node_modules => }/muri/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/muri/Makefile (100%) rename node_modules/{mongoose/node_modules => }/muri/README.md (100%) rename node_modules/{mongoose/node_modules => }/muri/index.js (100%) rename node_modules/{mongoose/node_modules => }/muri/lib/index.js (100%) rename node_modules/{mongoose/node_modules => }/muri/package.json (69%) rename node_modules/{mongoose/node_modules => }/muri/test/index.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/.dntrc (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/CHANGELOG.md (93%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/LICENSE.md (100%) create mode 100644 node_modules/nan/README.md rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/appveyor.yml (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/include_dirs.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/nan.h (95%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/nan_implementation_12_inl.h (96%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/kerberos/node_modules => }/nan/nan_implementation_pre_12_inl.h (96%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/nan_new.h (98%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/bson/node_modules => }/nan/nan_string_bytes.h (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/kerberos/node_modules => }/nan/package.json (56%) create mode 100644 node_modules/readable-stream/.airtap.yml create mode 100644 node_modules/readable-stream/.airtaprc create mode 100644 node_modules/readable-stream/.travis.yml create mode 100644 node_modules/readable-stream/CONTRIBUTING.md create mode 100644 node_modules/readable-stream/GOVERNANCE.md create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/errors-browser.js create mode 100644 node_modules/readable-stream/errors.js create mode 100644 node_modules/readable-stream/experimentalWarning.js create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/readable-stream/lib/_stream_passthrough.js (82%) create mode 100644 node_modules/readable-stream/lib/_stream_readable.js rename node_modules/{mongoose/node_modules/mongodb/node_modules => }/readable-stream/lib/_stream_transform.js (69%) create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/lib/internal/streams/async_iterator.js create mode 100644 node_modules/readable-stream/lib/internal/streams/buffer_list.js create mode 100644 node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 node_modules/readable-stream/lib/internal/streams/end-of-stream.js create mode 100644 node_modules/readable-stream/lib/internal/streams/pipeline.js create mode 100644 node_modules/readable-stream/lib/internal/streams/state.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 node_modules/readable-stream/package.json rename node_modules/{mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js => readable-stream/readable-browser.js} (72%) create mode 100644 node_modules/readable-stream/readable.js rename node_modules/{mongoose/node_modules => }/regexp-clone/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/History.md (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/Makefile (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/README.md (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/index.js (100%) rename node_modules/{mongoose/node_modules => }/regexp-clone/package.json (57%) rename node_modules/{mongoose/node_modules => }/regexp-clone/test/index.js (100%) rename node_modules/{mongoose/node_modules/mongodb/node_modules/readable-stream => safe-buffer}/LICENSE (62%) create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json rename node_modules/{mongoose/node_modules => }/sliced/.npmignore (100%) rename node_modules/{mongoose/node_modules => }/sliced/.travis.yml (100%) rename node_modules/{mongoose/node_modules => }/sliced/History.md (100%) rename node_modules/{mongoose/node_modules => }/sliced/LICENSE (100%) rename node_modules/{mongoose/node_modules => }/sliced/Makefile (100%) rename node_modules/{mongoose/node_modules => }/sliced/README.md (100%) rename node_modules/{mongoose/node_modules => }/sliced/bench.js (100%) rename node_modules/{mongoose/node_modules => }/sliced/component.json (100%) rename node_modules/{mongoose/node_modules => }/sliced/index.js (100%) rename node_modules/{mongoose/node_modules => }/sliced/lib/sliced.js (100%) create mode 100644 node_modules/sliced/package.json rename node_modules/{mongoose/node_modules => }/sliced/test/index.js (100%) create mode 100644 node_modules/string_decoder/.travis.yml create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/lib/string_decoder.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 package-lock.json diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE similarity index 89% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE rename to node_modules/bluebird/LICENSE index 9ed7b98..4182a1e 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/LICENSE +++ b/node_modules/bluebird/LICENSE @@ -1,11 +1,13 @@ -Copyright (c) 2014 Petka Antonov +The MIT License (MIT) + +Copyright (c) 2013-2015 Petka Antonov 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:

+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. diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md b/node_modules/bluebird/README.md similarity index 78% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md rename to node_modules/bluebird/README.md index c25e081..e1447bf 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/README.md +++ b/node_modules/bluebird/README.md @@ -1,19 +1,19 @@ -[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) - Promises/A+ logo +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) +**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) - -#Introduction +# Introduction Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance -#Topics +# Topics - [Features](#features) - [Quick start](#quick-start) @@ -34,9 +34,8 @@ Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-t - [Changelog](changelog.md) - [Optimization guide](#optimization-guide) -bluebird logo - -#Features: +# Features +bluebird logo - [Promises A+](http://promisesaplus.com) - [Synchronous inspection](API.md#synchronous-inspection) @@ -51,13 +50,13 @@ Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-t - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)! - [Practical debugging solutions and sane defaults](#error-handling) -- [Sick performance](benchmark/stats/latest.md) +- [Sick performance](benchmark/)
-#Quick start +# Quick start -##Node.js +## Node.js npm install bluebird @@ -67,47 +66,48 @@ Then: var Promise = require("bluebird"); ``` -##Browsers +## Browsers -Download the [bluebird.js](https://github.com/petkaantonov/bluebird/tree/master/js/browser) file. And then use a script tag: +There are many ways to use bluebird in browsers: -```html - -``` +- Direct downloads + - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) + - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) + - Core build [bluebird.core.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.js) + - Core build minified [bluebird.core.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js) +- You may use browserify on the main export +- You may use the [bower](http://bower.io) package. -The global variables `Promise` and `P` (alias for `Promise`) become available after the above script tag. +When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. -A [minimal bluebird browser build](#custom-builds) is ̃38.92KB minified*, 11.65KB gzipped and has no external dependencies. +A [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies. *Google Closure Compiler using Simple. -####Browser support +#### Browser support Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported. [![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov) -*IE7 and IE8 had to be removed from tests due to SauceLabs bug but are supported and pass all tests* - -**Note** that in ECMA-262, edition 3 (IE7, IE8 etc) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. +**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. -Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome and Firefox. - -Previously bluebird required es5-shim.js and es5-sham.js to support Edition 3 - these are **no longer required** as of **0.10.4**. +Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+. After quick start, see [API Reference and examples](API.md)
-#Support +# Support +- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js) - IRC: #promises @freenode - StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird) - Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)
-#What are promises and why should I use them? +# What are promises and why should I use them? You should use promises to turn this: @@ -137,8 +137,8 @@ fs.readFileAsync("file.json").then(JSON.parse).then(function(val) { .catch(SyntaxError, function(e) { console.error("invalid json in file"); }) -.catch(function(e){ - console.error("unable to read file") +.catch(function(e) { + console.error("unable to read file"); }); ``` @@ -156,7 +156,7 @@ catch(SyntaxError e) { console.error("invalid json in file"); } catch(Error e) { - console.error("unable to read file") + console.error("unable to read file"); } ``` @@ -172,7 +172,7 @@ mapSeries(URLs, function (URL, done) { var options = {}; needle.get(URL, options, function (error, response, body) { if (error) { - return done(error) + return done(error); } try { var ret = JSON.parse(body); @@ -184,13 +184,13 @@ mapSeries(URLs, function (URL, done) { }); }, function (err, results) { if (err) { - console.log(err) + console.log(err); } else { console.log('All Needle requests successful'); // results is a 1 to 1 mapping in order of URLs > needle.body processAndSaveAllInDB(results, function (err) { if (err) { - return done(err) + return done(err); } console.log('All Needle requests saved'); done(null); @@ -226,17 +226,17 @@ Also promises don't just give you correspondences for synchronous features but c More reading: - - [Promise nuggets](http://spion.github.io/promise-nuggets/) + - [Promise nuggets](https://promise-nuggets.github.io/) - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) -#Questions and issues +# Questions and issues -If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. +The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. -#Error handling +# Error handling This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled. @@ -282,7 +282,7 @@ Long stack traces cannot be disabled after being enabled, and cannot be enabled Long stack traces are enabled by default in the debug build. -####Expected and unexpected errors +#### Expected and unexpected errors A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about. @@ -316,7 +316,7 @@ getJSONFromSomewhere().then(function(jsonString) { }); ``` -Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. +Here any kind of unexpected error will be automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors? @@ -331,7 +331,7 @@ Example of such library is the node core library `fs`. So if we promisify it, we var fs = Promise.promisifyAll(require("fs")); fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { - console.log("Successful json") + console.log("Successful json"); }).catch(SyntaxError, function (e) { console.error("file contains invalid json"); }).catch(Promise.OperationalError, function (e) { @@ -353,7 +353,7 @@ See [API documentation for `.error()`](API.md#error-rejectedhandler----promise) Finally, Bluebird also supports predicate-based filters. If you pass a predicate function instead of an error type, the predicate will receive -the error as an argument. The return result will be used determine whether +the error as an argument. The return result will be used to determine whether the error handler should be called. Predicates should allow for very fine grained control over caught errors: @@ -381,7 +381,7 @@ request("http://www.google.com").then(function(contents){
-####How do long stack traces differ from e.g. Q? +#### How do long stack traces differ from e.g. Q? Bluebird attempts to have more elaborate traces. Consider: @@ -414,7 +414,7 @@ Promise.longStackTraces(); Promise.resolve().then(function outer() { return Promise.resolve().then(function inner() { return Promise.resolve().then(function evenMoreInner() { - a.b.c.d() + a.b.c.d(); }).catch(function catcher(e){ console.error(e.stack); }); @@ -439,73 +439,80 @@ A better and more practical example of the differences can be seen in gorgikosev
-#Development +# Development For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies. -Install [node](http://nodejs.org/), [npm](https://npmjs.org/), and [grunt](http://gruntjs.com/). +Install [node](http://nodejs.org/) and [npm](https://npmjs.org/) git clone git@github.com:petkaantonov/bluebird.git cd bluebird npm install -##Testing +## Testing -To run all tests, run `grunt test`. Note that 10 processes are created to run the tests in parallel. The `stdout` of tests is ignored by default and everything will stop at the first failure. If you want to run tests sequentially with all output, do: +To run all tests, run - grunt test --jobs=1 + node tools/test -You may also give a higher `--jobs` value to run more tests concurrently (and finish faster). +If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+: -Individual files can be run with `grunt test --run=filename` where `filename` is a test file name in `/test` folder or `/test/mocha` folder. The `.js` prefix is not needed. The dots for AP compliance tests are not needed, so to run `/test/mocha/2.3.3.js` for instance: + node-dev --harmony tools/test - grunt test --run=233 +You may specify an individual test file to run with the `--run` script flag: -When trying to get a test to pass, run only that individual test file with `--verbose` to see the output from that test: + node tools/test --run=cancel.js - grunt test --run=233 --verbose -The reason for the unusual way of testing is because the majority of tests are from different libraries using different testing frameworks and because it takes forever to test sequentially. +This enables output from the test and may give a better idea where the test is failing. The parameter to `--run` can be any file name located in `test/mocha` folder. +#### Testing in browsers -###Testing in browsers +To run the test in a browser instead of node, pass the flag `--browser` to the test tool -To test in browsers: + node tools/test --run=cancel.js --browser - cd browser - setup +This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled. -Then open the `index.html` in your browser. Requires bash (on windows the mingw32 that comes with git works fine too). +Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. -You may also [visit the github hosted page](http://petkaantonov.github.io/bluebird/browser/). +#### Supported options by the test tool -Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`. + + - `--run=String` - Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder). + - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter). + - `--browser` - Whether to compile tests for browsers. Default `false`. + - `--port=Number` - Port where local server is hosted when testing in browser. Default `9999` + - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`. + - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`. + - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`. + - `--js-hint` - Whether to run JSHint on source files. Default `true`. + - `--saucelabs` - Whether to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser. Default `false`. -##Benchmarks +## Benchmarks To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too). Node 0.11.2+ is required to run the generator examples. -###1\. DoxBee sequential +### 1\. DoxBee sequential Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections. Command: `bench doxbee` -###2\. Made-up parallel +### 2\. Made-up parallel This made-up scenario runs 15 shimmed queries in parallel. Command: `bench parallel` -##Custom builds +## Custom builds Custom builds for browsers are supported through a command-line utility. - - @@ -541,23 +548,34 @@ Make sure you have cloned the repo somewhere and did `npm install` successfully. After that you can run: - grunt build --features="core" + node tools/build --features="core" The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: - grunt build --features="core filter map reduce" + node tools/build --features="core filter map reduce" The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build a full version afterwards (after having taken a copy of the bluebird.js somewhere): - grunt build + node tools/build --debug --main --zalgo --browser --minify + +#### Supported options by the build tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. + + - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. + - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. + - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. + - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. + - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. + - `--features=String` - See [custom builds](#custom-builds)
-##For library authors +## For library authors Building a library that depends on bluebird? You should know about a few features. @@ -575,7 +593,7 @@ You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---prom
-##What is the sync build? +## What is the sync build? You may now use sync build by: @@ -630,13 +648,15 @@ function guessWhatItPrints( url ) { } ``` -#Optimization guide +# Optimization guide Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. A single cohesive guide compiled from the articles will probably be done eventually. -#License +# License + +The MIT License (MIT) Copyright (c) 2014 Petka Antonov diff --git a/node_modules/bluebird/changelog.md b/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..5f6e348 --- /dev/null +++ b/node_modules/bluebird/changelog.md @@ -0,0 +1,1723 @@ +## 2.10.2 (2015-10-01) + +Features: + + - `.timeout()` now takes a custom error object as second argument + +## 2.10.1 (2015-09-21) + + - Fix error "Cannot promisify an API that has normal methods with 'Async'-suffix" when promisifying certain objects with a custom promisifier + +## 2.10.0 (2015-09-08) + +Features: + + - `Promise.using` can now take the promises-for-resources as an array ([#733](.)). + - Browser builds for minimal core are now hosted on CDN ([#724](.)). + +Bugfixes: + + - Disabling debug mode with `BLUEBIRD_DEBUG=0` environment variable now works ([#719](.)). + - Fix unhandled rejection reporting when passing rejected promise to `.return()` ([#721](.)). + - Fix unbound promise's then handlers being called with wrong `this` value ([#738](.)). + +## 2.9.34 (2015-07-15) + +Bugfixes: + +- Correct domain for .map, .each, .filter, .reduce callbacks ([#701](.)). + - Preserve bound-with-promise promises across the entire chain ([#702](.)). + +## 2.9.33 (2015-07-09) + +Bugfixes: + + - Methods on `Function.prototype` are no longer promisified ([#680](.)). + +## 2.9.32 (2015-07-03) + +Bugfixes: + + - Fix `.return(primitiveValue)` returning a wrapped version of the primitive value when a Node.js domain is active ([#689](.)). + +## 2.9.31 (2015-07-03) + +Bugfixes: + + - Fix Promises/A+ compliance issue regarding circular thenables: the correct behavior is to go into an infinite loop instead of warning with an error (Fixes [#682](.)). + - Fix "(node) warning: possible EventEmitter memory leak detected" ([#661](.)). + - Fix callbacks sometimes being called with a wrong node.js domain ([#664](.)). + - Fix callbacks sometimes not being called at all in iOS 8.1 WebApp mode ([#666](.), [#687](.)). + +## 2.9.30 (2015-06-14) + +Bugfixes: + + - Fix regression with `promisifyAll` not promisifying certain methods + +## 2.9.29 (2015-06-14) + +Bugfixes: + + - Improve `promisifyAll` detection of functions that are class constructors. Fixes mongodb 2.x promisification. + +## 2.9.28 (2015-06-14) + +Bugfixes: + + - Fix handled rejection being reported as unhandled in certain scenarios when using [.all](.) or [Promise.join](.) ([#645](.)) + - Fix custom scheduler not being called in Google Chrome when long stack traces are enabled ([#650](.)) + +## 2.9.27 (2015-05-30) + +Bugfixes: + + - Fix `sinon.useFakeTimers()` breaking scheduler ([#631](.)) + +Misc: + + - Add nw testing facilities (`node tools/test --nw`) + +## 2.9.26 (2015-05-25) + +Bugfixes: + + - Fix crash in NW [#624](.) + - Fix [`.return()`](.) not supporting `undefined` as return value [#627](.) + +## 2.9.25 (2015-04-28) + +Bugfixes: + + - Fix crash in node 0.8 + +## 2.9.24 (2015-04-02) + +Bugfixes: + + - Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([#559](.), [#561](.), [#560](.)). + +## 2.9.23 (2015-04-02) + +Bugfixes: + + - Fix node.js domain propagation ([#521](.)). + +## 2.9.22 (2015-04-02) + + - Fix `.promisify` crashing in phantom JS ([#556](.)) + +## 2.9.21 (2015-03-30) + + - Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([#552](.)). + +## 2.9.20 (2015-03-29) + +Bugfixes: + + - Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled + +## 2.9.19 (2015-03-29) + +Bugfixes: + + - Fix crashing in Chrome when long stack traces are disabled + +## 2.9.18 (2015-03-29) + +Bugfixes: + + - Fix settlePromises using trampoline + +## 2.9.17 (2015-03-29) + + +Bugfixes: + + - Fix Chrome DevTools async stack traceability ([#542](.)). + +## 2.9.16 (2015-03-28) + +Features: + + - Use setImmediate if available + +## 2.9.15 (2015-03-26) + +Features: + + - Added `.asCallback` alias for `.nodeify`. + +Bugfixes: + + - Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [#534](.), [#525](.) + - Make progress a core feature. Fixes [#535](.) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. + +## 2.9.14 (2015-03-12) + +Bugfixes: + + - Always use process.nextTick. Fixes [#525](.) + +## 2.9.13 (2015-02-27) + +Bugfixes: + + - Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([#513](.)) + +## 2.9.12 (2015-02-19) + +Bugfixes: + + - Fix memory leak introduced in 2.9.0 ([#502](.)) + +## 2.9.11 (2015-02-19) + +Bugfixes: + + - Fix [#503](.) + +## 2.9.10 (2015-02-18) + +Bugfixes: + + - Fix [#501](.) + +## 2.9.9 (2015-02-12) + +Bugfixes: + + - Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. + +## 2.9.8 (2015-02-10) + +Bugfixes: + + - Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` + +## 2.9.7 (2015-02-08) + +Bugfixes: + + - Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. + - Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. + - Fix `process.nextTick` being used over `setImmediate` in node. + +## 2.9.6 (2015-02-02) + +Bugfixes: + + - Node environment detection can no longer be fooled + +## 2.9.5 (2015-02-02) + +Misc: + + - Warn when [`.then()`](.) is passed non-functions + +## 2.9.4 (2015-01-30) + +Bugfixes: + + - Fix [.timeout()](.) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. + +## 2.9.3 (2015-01-27) + +Bugfixes: + + - Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) + - Fix long stack trace support in recent firefox versions + +## 2.9.2 (2015-01-26) + +Bugfixes: + + - Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). + +Misc: + + - Add `"browser"` entry point to package.json + +## 2.9.1 (2015-01-24) + +Features: + + - If a bound promise is returned by the callback to [`Promise.method`](#promisemethodfunction-fn---function) and [`Promise.try`](#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise), the returned promise will be bound to the same value + +## 2.9.0 (2015-01-24) + +Features: + + - Add [`Promise.fromNode`](API.md#promisefromnodefunction-resolver---promise) + - Add new paramter `value` for [`Promise.bind`](API.md#promisebinddynamic-thisarg--dynamic-value---promise) + +Bugfixes: + + - Fix several issues with [`cancellation`](API.md#cancellation) and [`.bind()`](API.md#binddynamic-thisarg---promise) interoperation when `thisArg` is a promise or thenable + - Fix promises created in [`disposers`](API#disposerfunction-disposer---disposer) not having proper long stack trace context + - Fix [`Promise.join`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) sometimes passing the passed in callback function as the last argument to itself. + +Misc: + + - Reduce minified full browser build file size by not including unused code generation functionality. + - Major internal refactoring related to testing code and source code file layout + +## 2.8.2 (2015-01-20) + +Features: + + - [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers + +## 2.8.1 (2015-01-20) + +Bugfixes: + + - Fix long stack trace stiching consistency when rejected from thenables + +## 2.8.0 (2015-01-19) + +Features: + + - Major debuggability improvements: + - Long stack traces have been re-designed. They are now much more readable, + succint, relevant and consistent across bluebird features. + - Long stack traces are supported now in IE10+ + +## 2.7.1 (2015-01-15) + +Bugfixes: + + - Fix [#447](https://github.com/petkaantonov/bluebird/issues/447) + +## 2.7.0 (2015-01-15) + +Features: + + - Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) + - Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) + - [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification + - [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean + +Bugfixes: + + - Fix `.noConflict()` call signature ([#446]()) + - Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments + +## 2.6.4 (2015-01-12) + +Bugfixes: + + - `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. + +## 2.6.3 (2015-01-12) + +Bugfixes: + + - Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) + - Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) + - Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) + +## 2.6.2 (2015-01-07) + +Bugfixes: + + - Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) + +## 2.6.1 (2015-01-07) + +Bugfixes: + + - Fixed built browser files not being included in the git tag release for bower + +## 2.6.0 (2015-01-06) + +Features: + + - Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) + + +## 2.5.3 (2014-12-30) + +## 2.5.2 (2014-12-29) + +Bugfixes: + + - Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called + - Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption + - Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird + +## 2.5.1 (2014-12-29) + +Bugfixes: + + - Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise + +## 2.5.0 (2014-12-28) + +Features: + + - [`.get`](#API.md#https://github.com/petkaantonov/bluebird/blob/master/API.md#getstring-propertyname---promise) now supports negative indexing. + +Bugfixes: + + - Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise + - Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise + +## 2.4.3 (2014-12-28) + +Bugfixes: + + - Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). + +## 2.4.2 (2014-12-21) + +Bugfixes: + + - Fix bug where spread rejected handler is ignored in case of rejection + - Fix synchronous scheduler passed to `setScheduler` causing infinite loop + +## 2.4.1 (2014-12-20) + +Features: + + - Error messages now have links to wiki pages for additional information + - Promises now clean up all references (to handlers, child promises etc) as soon as possible. + +## 2.4.0 (2014-12-18) + +Features: + + - Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers + - Small performance improvements for all collection methods + - Promises now delete references to handlers attached to them as soon as possible + - Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) + +## 2.3.11 (2014-10-31) + +Bugfixes: + + - Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) + + +## 2.3.10 (2014-10-28) + +Features: + + - `Promise.method` no longer wraps primitive errors + - `Promise.try` no longer wraps primitive errors + +## 2.3.7 (2014-10-25) + +Bugfixes: + + - Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) + +## 2.3.6 (2014-10-15) + +Features: + + - Implement [`.reflect()`](API.md#reflect---promisepromiseinspection) + +## 2.3.5 (2014-10-06) + +Bugfixes: + + - Fix issue when promisifying methods whose names contain the string 'args' + +## 2.3.4 (2014-09-27) + + - `P` alias was not declared inside WebWorkers + +## 2.3.3 (2014-09-27) + +Bugfixes: + + - Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) + +## 2.3.2 (2014-08-25) + +Bugfixes: + + - `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions + +## 2.3.1 (2014-08-23) + +Features: + + - `.using` can now be used with disposers created from different bluebird copy + +## 2.3.0 (2014-08-13) + +Features: + + - [`.bind()`](API.md#binddynamic-thisarg---promise) and [`Promise.bind()`](API.md#promisebinddynamic-thisarg---promise) now await for the resolution of the `thisArg` if it's a promise or a thenable + +Bugfixes: + + - Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) + +## 2.2.2 (2014-07-14) + + - Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) + +## 2.2.1 (2014-07-07) + + - Fix multiline error messages only showing the first line + +## 2.2.0 (2014-07-07) + +Bugfixes: + + - `.any` and `.some` now consistently reject with RangeError when input array contains too few promises + - Fix iteration bug with `.reduce` when input array contains already fulfilled promises + +## 2.1.3 (2014-06-18) + +Bugfixes: + + - Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) + +## 2.1.2 (2014-06-15) + +Bugfixes: + + - Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) + +## 2.1.1 (2014-06-11) + +## 2.1.0 (2014-06-11) + +Features: + + - Add [`promisifier`](API.md#option-promisifier) option to `Promise.promisifyAll()` + - Improve performance of `.props()` and collection methods when used with immediate values + + +Bugfixes: + + - Fix a bug where .reduce calls the callback for an already visited item + - Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces + +Add undocumented experimental `yieldHandler` option to `Promise.coroutine` + +## 2.0.7 (2014-06-08) +## 2.0.6 (2014-06-07) +## 2.0.5 (2014-06-05) +## 2.0.4 (2014-06-05) +## 2.0.3 (2014-06-05) +## 2.0.2 (2014-06-04) +## 2.0.1 (2014-06-04) + +## 2.0.0 (2014-06-04) + +#What's new in 2.0 + +- [Resource management](API.md#resource-management) - never leak resources again +- [Promisification](API.md#promisification) on steroids - entire modules can now be promisified with one line of code +- [`.map()`](API.md#mapfunction-mapper--object-options---promise), [`.each()`](API.md#eachfunction-iterator---promise), [`.filter()`](API.md#filterfunction-filterer--object-options---promise), [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) reimagined from simple sugar to powerful concurrency coordination tools +- [API Documentation](API.md) has been reorganized and more elaborate examples added +- Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) +- Improved performance and readability + +Features: + +- Added [`using()`](API.md#promiseusingpromisedisposer-promise-promisedisposer-promise--function-handler---promise) and [`disposer()`](API.md#disposerfunction-disposer---disposer) +- [`.map()`](API.md#mapfunction-mapper--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.map()`](API.md#mapfunction-mapper--object-options---promise) +- [`.filter()`](API.md#filterfunction-filterer--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.filter()`](API.md#filterfunction-filterer--object-options---promise) +- [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) now calls the handler as soon as items in the input array become fulfilled, but in-order +- Added [`.each()`](API.md#eachfunction-iterator---promise) +- [`Promise.resolve()`](API.md#promiseresolvedynamic-value---promise) behaves like `Promise.cast`. `Promise.cast` deprecated. +- [Synchronous inspection](API.md#synchronous-inspection): Removed `.inspect()`, added [`.value()`](API.md#value---dynamic) and [`.reason()`](API.md#reason---dynamic) +- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) now takes a function as the last argument +- Added [`Promise.setScheduler()`](API.md#promisesetschedulerfunction-scheduler---void) +- [`.cancel()`](API.md#cancelerror-reason---promise) supports a custom cancellation reason +- [`.timeout()`](API.md#timeoutint-ms--string-message---promise) now cancels the promise instead of rejecting it +- [`.nodeify()`](API.md#nodeifyfunction-callback--object-options---promise) now supports passing multiple success results when mapping promises to nodebacks +- Added `suffix` and `filter` options to [`Promise.promisifyAll()`](API.md#promisepromisifyallobject-target--object-options---object) + +Breaking changes: + +- Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value +- `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order +- Removed the `.inspect()` method +- Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](API.md#promisecoroutineaddyieldhandlerfunction-handler---void) to configure the old behavior (or any behavior you want). +- [`.any()`](API.md#any---promise) and [`.some()`](API.md#someint-count---promise) no longer use an array as the rejection reason. [`AggregateError`](API.md#aggregateerror) is used instead. + + +## 1.2.4 (2014-04-27) + +Bugfixes: + + - Fix promisifyAll causing a syntax error when a method name is not a valid identifier + - Fix syntax error when es5.js is used in strict mode + +## 1.2.3 (2014-04-17) + +Bugfixes: + + - Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) + +## 1.2.2 (2014-04-09) + +Bugfixes: + + - Promisified methods from promisifyAll no longer call the original method when it is overriden + - Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` + +## 1.2.1 (2014-03-31) + +Bugfixes: + + - Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) + +## 1.2.0 (2014-03-29) + +Features: + + - New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) + - New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) + - New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) + - `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). + +Bugfixes: + + - Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) + - Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) + +## 1.1.1 (2014-03-18) + +Bugfixes: + + - [#138](https://github.com/petkaantonov/bluebird/issues/138) + - [#144](https://github.com/petkaantonov/bluebird/issues/144) + - [#148](https://github.com/petkaantonov/bluebird/issues/148) + - [#151](https://github.com/petkaantonov/bluebird/issues/151) + +## 1.1.0 (2014-03-08) + +Features: + + - Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) + - Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) + - Deprecate `Promise.prototype.spawn` + +Bugfixes: + + - Fix already rejected promises being reported as unhandled when handled through collection methods + - Fix browserisfy crashing from checking `process.version.indexOf` + +## 1.0.8 (2014-03-03) + +Bugfixes: + + - Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx + +## 1.0.7 (2014-02-25) + +Bugfixes: + + - Fix handled errors being reported + +## 1.0.6 (2014-02-17) + +Bugfixes: + + - Fix bug with unhandled rejections not being reported + when using `Promise.try` or `Promise.method` without + attaching further handlers + +## 1.0.5 (2014-02-15) + +Features: + + - Node.js performance: promisified functions try to check amount of passed arguments in most optimal order + - Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) + +## 1.0.4 (2014-02-09) + +Features: + + - Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error + - Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation + +Bugfixes: + + - Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler + +## 1.0.3 (2014-02-05) + +Bugfixes: + + - [#93](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.2 (2014-02-04) + +Features: + + - Significantly improve performance of foreign bluebird thenables + +Bugfixes: + + - [#88](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.1 (2014-01-28) + +Features: + + - Error objects that have property `.isAsync = true` will now be caught by `.error()` + +Bugfixes: + + - Fix TypeError and RangeError shims not working without `new` operator + +## 1.0.0 (2014-01-12) + +Features: + + - `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. + - Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. + +Bugfixes: + + - [#58](https://github.com/petkaantonov/bluebird/issues/58) + - [#61](https://github.com/petkaantonov/bluebird/issues/61) + - [#64](https://github.com/petkaantonov/bluebird/issues/64) + - [#60](https://github.com/petkaantonov/bluebird/issues/60) + +## 0.11.6-1 (2013-12-29) + +## 0.11.6-0 (2013-12-29) + +Features: + + - You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. + + - `.error()` now catches additional sources of rejections: + + - Rejections originating from `Promise.reject` + + - Rejections originating from thenables using + the `reject` callback + + - Rejections originating from promisified callbacks + which use the `errback` argument + + - Rejections originating from `new Promise` constructor + where the `reject` callback is called explicitly + + - Rejections originating from `PromiseResolver` where + `.reject()` method is called explicitly + +Bugfixes: + + - Fix `captureStackTrace` being called when it was `null` + - Fix `Promise.map` not unwrapping thenables + +## 0.11.5-1 (2013-12-15) + +## 0.11.5-0 (2013-12-03) + +Features: + + - Improve performance of collection methods + - Improve performance of promise chains + +## 0.11.4-1 (2013-12-02) + +## 0.11.4-0 (2013-12-02) + +Bugfixes: + + - Fix `Promise.some` behavior with arguments like negative integers, 0... + - Fix stack traces of synchronously throwing promisified functions' + +## 0.11.3-0 (2013-12-02) + +Features: + + - Improve performance of generators + +Bugfixes: + + - Fix critical bug with collection methods. + +## 0.11.2-0 (2013-12-02) + +Features: + + - Improve performance of all collection methods + +## 0.11.1-0 (2013-12-02) + +Features: + +- Improve overall performance. +- Improve performance of promisified functions. +- Improve performance of catch filters. +- Improve performance of .finally. + +Bugfixes: + +- Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. +- Fix `.finally()` not converting thenables returned from the handler to promises. +- `.spread()` now rejects if the ultimate value given to it is not spreadable. + +## 0.11.0-0 (2013-12-02) + +Features: + + - Improve overall performance when not using `.bind()` or cancellation. + - Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) + - [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) + - [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) + - [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) + +## 0.10.14-0 (2013-12-01) + +Bugfixes: + + - Fix race condition when mixing 3rd party asynchrony. + +## 0.10.13-1 (2013-11-30) + +## 0.10.13-0 (2013-11-30) + +Bugfixes: + + - Fix another bug with progression. + +## 0.10.12-0 (2013-11-30) + +Bugfixes: + + - Fix bug with progression. + +## 0.10.11-4 (2013-11-29) + +## 0.10.11-2 (2013-11-29) + +Bugfixes: + + - Fix `.race()` not propagating bound values. + +## 0.10.11-1 (2013-11-29) + +Features: + + - Improve performance of `Promise.race` + +## 0.10.11-0 (2013-11-29) + +Bugfixes: + + - Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. + +## 0.10.10-0 (2013-11-28) + +Features: + + - Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. + +## 0.10.9-1 (2013-11-27) + +Bugfixes: + + - Fail early when `new Promise` is constructed incorrectly + +## 0.10.9-0 (2013-11-27) + +Bugfixes: + + - Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) + - All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection + +## 0.10.8-0 (2013-11-25) + +Features: + + - All static collection methods take thenable-for-collection + +## 0.10.7-0 (2013-11-25) + +Features: + + - throw TypeError when thenable resolves with itself + - Make .race() and Promise.race() forever pending on empty collections + +## 0.10.6-0 (2013-11-25) + +Bugfixes: + + - Promise.resolve and PromiseResolver.resolve follow thenables too. + +## 0.10.5-0 (2013-11-24) + +Bugfixes: + + - Fix infinite loop when thenable resolves with itself + +## 0.10.4-1 (2013-11-24) + +Bugfixes: + + - Fix a file missing from build. (Critical fix) + +## 0.10.4-0 (2013-11-24) + +Features: + + - Remove dependency of es5-shim and es5-sham when using ES3. + +## 0.10.3-0 (2013-11-24) + +Features: + + - Improve performance of `Promise.method` + +## 0.10.2-1 (2013-11-24) + +Features: + + - Rename PromiseResolver#asCallback to PromiseResolver#callback + +## 0.10.2-0 (2013-11-24) + +Features: + + - Remove memoization of thenables + +## 0.10.1-0 (2013-11-21) + +Features: + + - Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. + +## 0.10.0-1 (2013-11-17) + +## 0.10.0-0 (2013-11-17) + +Features: + + - Implement `Promise.method()` + - Implement `.return()` + - Implement `.throw()` + +Bugfixes: + + - Fix promises being able to use themselves as resolution or follower value + +## 0.9.11-1 (2013-11-14) + +Features: + + - Implicit `Promise.all()` when yielding an array from generators + +## 0.9.11-0 (2013-11-13) + +Bugfixes: + + - Fix `.spread` not unwrapping thenables + +## 0.9.10-2 (2013-11-13) + +Features: + + - Improve performance of promisified functions on V8 + +Bugfixes: + + - Report unhandled rejections even when long stack traces are disabled + - Fix `.error()` showing up in stack traces + +## 0.9.10-1 (2013-11-05) + +Bugfixes: + + - Catch filter method calls showing in stack traces + +## 0.9.10-0 (2013-11-05) + +Bugfixes: + + - Support primitives in catch filters + +## 0.9.9-0 (2013-11-05) + +Features: + + - Add `Promise.race()` and `.race()` + +## 0.9.8-0 (2013-11-01) + +Bugfixes: + + - Fix bug with `Promise.try` not unwrapping returned promises and thenables + +## 0.9.7-0 (2013-10-29) + +Bugfixes: + + - Fix bug with build files containing duplicated code for promise.js + +## 0.9.6-0 (2013-10-28) + +Features: + + - Improve output of reporting unhandled non-errors + - Implement RejectionError wrapping and `.error()` method + +## 0.9.5-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + +## 0.9.4-1 (2013-10-27) + +## 0.9.4-0 (2013-10-27) + +Bugfixes: + + - Rollback non-working multiple fresh copies feature + +## 0.9.3-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + - Add more components to customized builds + +## 0.9.2-1 (2013-10-25) + +## 0.9.2-0 (2013-10-25) + +Features: + + - Allow custom builds + +## 0.9.1-1 (2013-10-22) + +Bugfixes: + + - Fix unhandled rethrown exceptions not reported + +## 0.9.1-0 (2013-10-22) + +Features: + + - Improve performance of `Promise.try` + - Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. + +## 0.9.0-0 (2013-10-18) + +Features: + + - Implement `.bind` and `Promise.bind` + +Bugfixes: + + - Fix `.some()` when argument is a pending promise that later resolves to an array + +## 0.8.5-1 (2013-10-17) + +Features: + + - Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable + +## 0.8.5-0 (2013-10-16) + +Features: + + - Improve performance of all collection methods + +Bugfixes: + + - Fix .finally passing the value to handlers + - Remove kew from benchmarks due to bugs in the library breaking the benchmark + - Fix some bluebird library calls potentially appearing in stack traces + +## 0.8.4-1 (2013-10-15) + +Bugfixes: + + - Fix .pending() call showing in long stack traces + +## 0.8.4-0 (2013-10-15) + +Bugfixes: + + - Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections + +## 0.8.3-3 (2013-10-14) + +Bugfixes: + + - Fix AMD-declaration using named module. + +## 0.8.3-2 (2013-10-14) + +Features: + + - The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` + +## 0.8.3-1 (2013-10-14) + +Bugfixes: + + - Fix memory leak when using the same promise to attach handlers over and over again + +## 0.8.3-0 (2013-10-13) + +Features: + + - Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. + +Bugfixes: + + - Fix bug with .some returning garbage when sparse arrays have rejections + +## 0.8.2-2 (2013-10-13) + +Features: + + - Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value + +## 0.8.2-1 (2013-10-12) + +Bugfixes: + + - Fix .npmignore having irrelevant files + +## 0.8.2-0 (2013-10-12) + +Features: + + - Improve performance of `.some()` + +## 0.8.1-0 (2013-10-11) + +Bugfixes: + + - Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. + +## 0.8.0-3 (2013-10-10) + +Features: + + - Add `.asCallback` property to `PromiseResolver`s + +## 0.8.0-2 (2013-10-10) + +## 0.8.0-1 (2013-10-09) + +Features: + + - Improve overall performance. Be able to sustain infinite recursion when using promises. + +## 0.8.0-0 (2013-10-09) + +Bugfixes: + + - Fix stackoverflow error when function calls itself "synchronously" from a promise handler + +## 0.7.12-2 (2013-10-09) + +Bugfixes: + + - Fix safari 6 not using `MutationObserver` as a scheduler + - Fix process exceptions interfering with internal queue flushing + +## 0.7.12-1 (2013-10-09) + +Bugfixes: + + - Don't try to detect if generators are available to allow shims to be used + +## 0.7.12-0 (2013-10-08) + +Features: + + - Promisification now consider all functions on the object and its prototype chain + - Individual promisifcation uses current `this` if no explicit receiver is given + - Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. + +Bugfixes: + + - Fix runtime APIs throwing synchronous errors + +## 0.7.11-0 (2013-10-08) + +Features: + + - Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects + - Coroutines now throw error when a non-promise is `yielded` + +## 0.7.10-1 (2013-10-05) + +Features: + + - Make tests pass Internet Explorer 8 + +## 0.7.10-0 (2013-10-05) + +Features: + + - Create browser tests + +## 0.7.9-1 (2013-10-03) + +Bugfixes: + + - Fix promise cast bug when thenable fulfills using itself as the fulfillment value + +## 0.7.9-0 (2013-10-03) + +Features: + + - More performance improvements when long stack traces are enabled + +## 0.7.8-1 (2013-10-02) + +Features: + + - Performance improvements when long stack traces are enabled + +## 0.7.8-0 (2013-10-02) + +Bugfixes: + + - Fix promisified methods not turning synchronous exceptions into rejections + +## 0.7.7-1 (2013-10-02) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.7-0 (2013-10-01) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.6-0 (2013-09-29) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.5-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.2-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-5 (2013-09-26) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-4 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-3 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-2 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-1 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-0 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-1 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-0 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-2 (2013-09-20) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-4 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-3 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-2 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-1 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-0 (2013-09-15) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-1 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.1-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.0-0 (2013-09-13) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-6 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-5 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-4 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-3 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-2 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.7-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-0 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-0 (2013-09-09) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-1 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-0 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.3-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.2-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.1-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.0-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.4.0-0 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0-1 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0 (2013-09-06) diff --git a/node_modules/bluebird/js/browser/bluebird.js b/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..58a08a3 --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,4887 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Petka Antonov + * + * 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. + * + */ +/** + * bluebird build version 2.10.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +function AsyncInvokeLater(fn, receiver, arg) { + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + this._normalQueue._pushOne(promise); + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; + +},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + maybePromise._then(function() { + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._resolveCallback(value); + } + return ret; +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util.js":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; + +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = _dereq_("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundValue(); + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false; + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ignoreRejections = function() { + this._unsetRejectionIsUnhandled(); + this._bitField = this._bitField | 16777216; +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 16777216) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } else if (value instanceof Promise) { + value._ignoreRejections(); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./util.js":38}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; + +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +function subError(nameProperty, defaultMessage) { + function SubError(message) { + if (!(this instanceof SubError)) return new SubError(message); + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +var CancellationError = subError("CancellationError", "cancellation error"); +var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} + +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); + this.cause = message; + this["isOperational"] = true; + + if (message instanceof Error) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + +} +inherits(OperationalError, Error); + +var errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; + +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundValue()) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundValue(), value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; + +},{"./util.js":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; + + var callback = this._callback; + var receiver = this._promise._boundValue(); + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + + } +}; + +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); + } +}; + +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; + } + ret.length = j; + this._resolve(ret); +}; + +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; +}; + +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} + +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + return map(this, fn, options, null).promise(); +}; + +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; + + +}; + +},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; + +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; + +var util = _dereq_("./util.js"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var UNDEFINED_BINDING = {}; +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = target._addCallbacks(didFulfill, + didReject, + didProgress, + ret, + receiver, + getDomain()); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._boundValue = function() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, progress, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this._progressHandler0 = + domain === null ? progress : domain.bind(progress); + } + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this[base + 2] = + domain === null ? progress : domain.bind(progress); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundValue(), value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./progress.js")(Promise, PromiseArray); +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./cancel.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._ignoreRejections(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util.js":38}],25:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = _dereq_("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + name !== "constructor"; +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; + } +} + +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; +} +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } + } + } + } +} + +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; + } + return ret.replace("{{args}}", args).replace(", ", comma); + } + + function generateArgumentSwitchCase() { + var ret = ""; + for (var i = 0; i < argumentOrder.length; ++i) { + ret += "case " + argumentOrder[i] +":" + + generateCallForArgumentCount(argumentOrder[i]); + } + + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { + if (typeof fn !== "function") { + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + if (isPromisified(fn)) { + return fn; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); + } + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); + } + } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],29:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; + +},{"./util.js":38}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; + +},{"./util.js":38}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util.js":38}],36:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + + var err; + if(!util.isPrimitive(message) && (message instanceof Error)) { + err = message; + } else { + if (typeof message !== "string") { + message = "operation timed out"; + } + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); + } + inspections[i] = inspection._settledValue; + } + return inspections; + } + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); + } + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret.promise; + } + + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } + + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + Disposer.prototype.data = function () { + return this._data; + }; + + Disposer.prototype.promise = function () { + return this._promise; + }; + + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = input[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = spreadArgs + ? fn.apply(undefined, vals) : fn.call(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5.js":14}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..9d066dd --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 Petka Antonov + * + * 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. + * + */ +/** + * bluebird build version 2.10.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(r){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},l.hasDevTools?(u.isStatic&&(u=function(t){setTimeout(t,0)}),r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):this._schedule(function(){setTimeout(function(){t.call(e,r)},100)})},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):this._schedule(function(){t.call(e,r)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(u._setBoundTo(a),a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return s._setBoundTo(o),o instanceof t?o._then(function(){s._resolveCallback(i)},s._reject,s._progress,s,null):s._resolveCallback(i),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i||"number"!=typeof Error.stackTraceLimit?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundValue(),u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=e._getDomain,s=t("./async.js"),a=t("./errors.js").Warning,u=t("./util.js"),c=u.canAttachTrace,l=!1||u.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return u.isNode&&0==process.env.BLUEBIRD_DEBUG&&(l=!1),l&&s.disableTrampolineIfNecessary(),e.prototype._ignoreRejections=function(){this._unsetRejectionIsUnhandled(),this._bitField=16777216|this._bitField},e.prototype._ensurePossibleRejectionHandled=function(){0===(16777216&this._bitField)&&(this._setRejectionIsUnhandled(),s.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return l&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(l&&c(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);u.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),u.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new a(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){var e=o();i="function"==typeof t?null===e?t:e.bind(t):void 0},e.onUnhandledRejectionHandled=function(t){var e=o();n="function"==typeof t?null===e?t:e.bind(t):void 0},e.longStackTraces=function(){if(s.haveItemsQueued()&&l===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");l=r.isSupported(),l&&s.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return l&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},l=!1),function(){return l}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive;e.exports=function(t){var e=function(){return this},r=function(){throw this},i=function(){},o=function(){throw void 0},s=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(r){return void 0===r?this.then(i):n(r)?this._then(s(r,2),void 0,void 0,void 0,void 0):(r instanceof t&&r._ignoreRejections(),this._then(e,void 0,void 0,r,void 0))},t.prototype["throw"]=t.prototype.thenThrow=function(t){return void 0===t?this.then(o):n(t)?this._then(s(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace();var i=c();this._callback=null===i?e:i.bind(e),this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:d,l.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=e._getDomain,l=t("./async.js"),h=t("./util.js"),p=h.tryCatch,f=h.errorObj,_={},d=[];h.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===_){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundValue();this._promise._pushContext();var l=p(u).call(c,t,r,o);if(this._promise._popContext(),l===f)return this._reject(l.e);var h=i(l,this._promise);if(h instanceof e){if(h=h._target(),h._isPending())return a>=1&&this._inFlight++,n[r]=_,h._proxyPromiseArray(this,r);if(!h._isFulfilled())return this._reject(h._reason());l=h._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundValue(),[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundValue(),i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundValue(),t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new h("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new h("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==p&&this._resolveFromResolver(t)}function r(t){var r=new e(p);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n,i=function(){return new h("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},o=function(){return new e.PromiseInspection(this._target())},s=function(t){return e.reject(new h(t))},a=t("./util.js");n=a.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},a.notEnumerableProp(e,"_getDomain",n);var u={},c=t("./async.js"),l=t("./errors.js"),h=e.TypeError=l.TypeError;e.RangeError=l.RangeError,e.CancellationError=l.CancellationError,e.TimeoutError=l.TimeoutError,e.OperationalError=l.OperationalError,e.RejectionError=l.OperationalError,e.AggregateError=l.AggregateError;var p=function(){},f={},_={e:null},d=t("./thenables.js")(e,p),v=t("./promise_array.js")(e,p,d,s),y=t("./captured_trace.js")(),g=t("./debuggability.js")(e,y),m=t("./context.js")(e,y,g),j=t("./catch_filter.js")(_),b=t("./promise_resolver.js"),w=b._nodebackForPromise,k=a.errorObj,E=a.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new h("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new j(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(o,o,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(g()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+a.classString(t);arguments.length>1&&(n+=", "+a.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0); +n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,f,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new v(this).promise()},e.prototype.error=function(t){return this.caught(a.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(p),n=E(t)(w(r));return n===k&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new v(t).promise()},e.defer=e.pending=function(){var t=new e(p);return new b(t)},e.cast=function(t){var r=d(t);if(!(r instanceof e)){var n=r;r=new e(p),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(p);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new h("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=c._schedule;return c._schedule=t,e},e.prototype._then=function(t,r,i,o,s){var a=void 0!==s,u=a?s:new e(p);a||(u._propagateFrom(this,5),u._captureStackTrace());var l=this._target();l!==this&&(void 0===o&&(o=this._boundTo),a||u._setIsMigrated());var h=l._addCallbacks(t,r,i,u,o,n());return l._isResolved()&&!l._isSettlePromisesQueued()&&c.invoke(l._settlePromiseAtPostResolution,l,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return e===u?void 0:void 0===e&&this._isBound()?this._boundValue():e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._boundValue=function(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),void 0===a&&(a=u),this._addCallbacks(n,i,o,s,a,null)},e.prototype._addCallbacks=function(t,e,r,n,i,o){var s=this._length();if(s>=131066&&(s=0,this._setLength(0)),0===s)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=null===o?t:o.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===o?e:o.bind(e)),"function"==typeof r&&(this._progressHandler0=null===o?r:o.bind(r));else{var a=5*s-5;this[a+3]=n,this[a+4]=i,"function"==typeof t&&(this[a+0]=null===o?t:o.bind(t)),"function"==typeof e&&(this[a+1]=null===o?e:o.bind(e)),"function"==typeof r&&(this[a+2]=null===o?r:o.bind(r))}return this._setLength(s+1),s},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(i(),!1,!0);var n=d(t,this);if(!(n instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(n,o);var s=n._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||a.markAsOriginatingFromRejection(t);var n=a.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=E(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===k&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,n){if(!n._isRejected()){n._pushContext();var o;if(o=e!==f||this._isRejected()?E(t).call(e,r):E(t).apply(this._boundValue(),r),n._popContext(),o===k||o===n||o===_){var s=o===n?i():o.e;n._rejectCallback(s,!1,!0)}else n._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),c.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,a=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,a,s,r):i.call(a,s,r):a instanceof v?a._isResolved()||(this._isFulfilled()?a._promiseFulfilled(s,r):a._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&c.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){c.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=i();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=a.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=i();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void c.throwLater(function(t){throw"stack"in t&&c.invokeFirst(y.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},a.notEnumerableProp(e,"_makeSelfResolutionError",i),t("./progress.js")(e,v),t("./method.js")(e,p,d,s),t("./bind.js")(e,p,d),t("./finally.js")(e,_,d),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,v,d,p),e.Promise=e,t("./map.js")(e,v,s,d,p),t("./cancel.js")(e),t("./using.js")(e,s,d,m),t("./generators.js")(e,s,p,d),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,v,d,s),t("./race.js")(e,p,d,s),t("./reduce.js")(e,v,s,d,p),t("./settle.js")(e,v),t("./some.js")(e,v,s),t("./promisify.js")(e,p),t("./any.js")(e),t("./each.js")(e,p),t("./timers.js")(e,p),t("./filter.js")(e,p),a.toFastProperties(e),a.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(p)),y.setBounds(c.firstLineError,a.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._ignoreRejections():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!w.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;if(n===F)t[h]=F(c,p,c,l,e);else{var _=n(l,function(){return F(c,p,c,l,e)});f.notEnumerableProp(_,"__isPromisified__",!0),t[h]=_}}return f.toFastProperties(t),t}function l(t,e){return F(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],w=new RegExp("^(?:"+b.join("|")+")$"),k=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},F=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=k);var i=e.promisifier;if("function"!=typeof i&&(i=F),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),h=!1,p=u instanceof e;p&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),h=!0)),p||this._zerothIsAccum||(this._gotAccum=!0);var f=c();this._callback=null===f?r:f.bind(r),this._accum=n,h||l.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=e._getDomain,l=t("./async.js"),h=t("./util.js"),p=h.tryCatch,f=h.errorObj;h.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var h,_=this._callback,d=this._promise._boundValue(),v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),h=p(_).call(d,t,v,s)):h=p(_).call(d,this._accum,t,v,s),this._promise._popContext(),h===f)return this._reject(h.e);var y=i(h,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());h=y._value()}this._reducingIndex=v+1,this._accum=h}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=t("./util"),i=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(n.isNode&&"undefined"==typeof MutationObserver){var o=global.setImmediate,s=process.nextTick;r=n.isRecentNode?function(t){o.call(global,t)}:function(t){s.call(process,t)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:i:(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0);e.exports=r},{"./util":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(t){l&&(l._resolveCallback(t),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){var r;!o.isPrimitive(e)&&e instanceof Error?r=e:("string"!=typeof e&&(e="operation timed out"),r=new s(e)),o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");var s,a=!0;2===t&&Array.isArray(arguments[0])?(s=arguments[0],t=s.length,a=!1):(s=arguments,t--);for(var u=new Array(t),p=0;t>p;++p){var _=s[p];if(h.isDisposer(_)){var d=_;_=_.promise(),_._setDisposable(d) +}else{var v=n(_);v instanceof e&&(_=v._then(f,null,null,{resources:u,index:p},void 0))}u[p]=_}var y=e.settle(u).then(o).then(function(t){y._pushContext();var e;try{e=a?i.apply(void 0,t):i.call(void 0,t)}finally{y._popContext()}return e})._then(c,l,void 0,u,void 0);return u.promise=y,y},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict";function n(){try{var t=C;return C=null,t.apply(this,arguments)}catch(e){return F.e=e,F}}function i(t){return C=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype),r=w.isES5&&e.length>1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=x.test(t+"")&&w.names(t).length>0;if(r||n||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;i10||t[0]>0}(),A.isNode&&A.toFastProperties(process);try{throw new Error}catch(O){A.lastLineError=O}e.exports=A},{"./es5.js":14}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/main/any.js b/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/node_modules/bluebird/js/main/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js b/node_modules/bluebird/js/main/assert.js similarity index 57% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js rename to node_modules/bluebird/js/main/assert.js index 86ac49e..a98955c 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/assert.js +++ b/node_modules/bluebird/js/main/assert.js @@ -1,25 +1,3 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ "use strict"; module.exports = (function(){ var AssertionError = (function() { @@ -72,10 +50,6 @@ return function assert(boolExpr, message) { if (Error.captureStackTrace) { Error.captureStackTrace(ret, assert); } - if (console && console.error) { - console.error(ret.stack + ""); - } throw ret; - }; })(); diff --git a/node_modules/bluebird/js/main/async.js b/node_modules/bluebird/js/main/async.js new file mode 100644 index 0000000..0104459 --- /dev/null +++ b/node_modules/bluebird/js/main/async.js @@ -0,0 +1,150 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule.js"); +var Queue = require("./queue.js"); +var util = require("./util.js"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.enableTrampoline = function() { + if (!this._trampolineEnabled) { + this._trampolineEnabled = true; + this._schedule = function(fn) { + setTimeout(fn, 0); + }; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +function AsyncInvokeLater(fn, receiver, arg) { + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + this._normalQueue._pushOne(promise); + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; diff --git a/node_modules/bluebird/js/main/bind.js b/node_modules/bluebird/js/main/bind.js new file mode 100644 index 0000000..9d8257a --- /dev/null +++ b/node_modules/bluebird/js/main/bind.js @@ -0,0 +1,72 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + maybePromise._then(function() { + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._resolveCallback(value); + } + return ret; +}; +}; diff --git a/node_modules/bluebird/js/main/bluebird.js b/node_modules/bluebird/js/main/bluebird.js new file mode 100644 index 0000000..ed6226e --- /dev/null +++ b/node_modules/bluebird/js/main/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/bluebird/js/main/call_get.js b/node_modules/bluebird/js/main/call_get.js new file mode 100644 index 0000000..62c166d --- /dev/null +++ b/node_modules/bluebird/js/main/call_get.js @@ -0,0 +1,123 @@ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} + +module.exports = function(Promise) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!false) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; + } + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; + } + } + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!false) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } + } + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; + +function namedGetter(obj) { + return obj[this]; +} +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; diff --git a/node_modules/bluebird/js/main/cancel.js b/node_modules/bluebird/js/main/cancel.js new file mode 100644 index 0000000..9eb40b6 --- /dev/null +++ b/node_modules/bluebird/js/main/cancel.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = function(Promise) { +var errors = require("./errors.js"); +var async = require("./async.js"); +var CancellationError = errors.CancellationError; + +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; diff --git a/node_modules/bluebird/js/main/captured_trace.js b/node_modules/bluebird/js/main/captured_trace.js new file mode 100644 index 0000000..802acd3 --- /dev/null +++ b/node_modules/bluebird/js/main/captured_trace.js @@ -0,0 +1,493 @@ +"use strict"; +module.exports = function() { +var async = require("./async.js"); +var util = require("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +}; + +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} + +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} + +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; + } + } + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } + + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; diff --git a/node_modules/bluebird/js/main/catch_filter.js b/node_modules/bluebird/js/main/catch_filter.js new file mode 100644 index 0000000..df12733 --- /dev/null +++ b/node_modules/bluebird/js/main/catch_filter.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util.js"); +var errors = require("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = require("./es5.js").keys; +var TypeError = errors.TypeError; + +function CatchFilter(instances, callback, promise) { + this._instances = instances; + this._callback = callback; + this._promise = promise; +} + +function safePredicate(predicate, e) { + var safeObject = {}; + var retfilter = tryCatch(predicate).call(safeObject, e); + + if (retfilter === errorObj) return retfilter; + + var safeKeys = keys(safeObject); + if (safeKeys.length) { + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); + return errorObj; + } + return retfilter; +} + +CatchFilter.prototype.doFilter = function (e) { + var cb = this._callback; + var promise = this._promise; + var boundTo = promise._boundValue(); + for (var i = 0, len = this._instances.length; i < len; ++i) { + var item = this._instances[i]; + var itemIsErrorType = item === Error || + (item != null && item.prototype instanceof Error); + + if (itemIsErrorType && e instanceof item) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } else if (typeof item === "function" && !itemIsErrorType) { + var shouldHandle = safePredicate(item, e); + if (shouldHandle === errorObj) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(boundTo, e); + if (ret === errorObj) { + NEXT_FILTER.e = ret.e; + return NEXT_FILTER; + } + return ret; + } + } + } + NEXT_FILTER.e = e; + return NEXT_FILTER; +}; + +return CatchFilter; +}; diff --git a/node_modules/bluebird/js/main/context.js b/node_modules/bluebird/js/main/context.js new file mode 100644 index 0000000..ccd7702 --- /dev/null +++ b/node_modules/bluebird/js/main/context.js @@ -0,0 +1,38 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; diff --git a/node_modules/bluebird/js/main/debuggability.js b/node_modules/bluebird/js/main/debuggability.js new file mode 100644 index 0000000..106baf6 --- /dev/null +++ b/node_modules/bluebird/js/main/debuggability.js @@ -0,0 +1,162 @@ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var getDomain = Promise._getDomain; +var async = require("./async.js"); +var Warning = require("./errors.js").Warning; +var util = require("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false; + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ignoreRejections = function() { + this._unsetRejectionIsUnhandled(); + this._bitField = this._bitField | 16777216; +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 16777216) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; diff --git a/node_modules/bluebird/js/main/direct_resolve.js b/node_modules/bluebird/js/main/direct_resolve.js new file mode 100644 index 0000000..054685a --- /dev/null +++ b/node_modules/bluebird/js/main/direct_resolve.js @@ -0,0 +1,63 @@ +"use strict"; +var util = require("./util.js"); +var isPrimitive = util.isPrimitive; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } else if (value instanceof Promise) { + value._ignoreRejections(); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; diff --git a/node_modules/bluebird/js/main/each.js b/node_modules/bluebird/js/main/each.js new file mode 100644 index 0000000..a37e22c --- /dev/null +++ b/node_modules/bluebird/js/main/each.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js b/node_modules/bluebird/js/main/errors.js similarity index 55% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js rename to node_modules/bluebird/js/main/errors.js index 4ea7b6d..c334bb1 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors.js +++ b/node_modules/bluebird/js/main/errors.js @@ -1,59 +1,20 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ "use strict"; -var Objectfreeze = require("./es5.js").freeze; +var es5 = require("./es5.js"); +var Objectfreeze = es5.freeze; var util = require("./util.js"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof OperationalError) || - e["isOperational"] === true); -} - -function isError(obj) { - return obj instanceof Error; -} - -function canAttach(obj) { - return isError(obj); -} - function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); - this.message = typeof message === "string" ? message : defaultMessage; - this.name = nameProperty; + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); } } inherits(SubError, Error); @@ -61,6 +22,7 @@ function subError(nameProperty, defaultMessage) { } var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); @@ -81,7 +43,12 @@ for (var i = 0; i < methods.length; ++i) { } } -AggregateError.prototype.length = 0; +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { @@ -103,14 +70,16 @@ AggregateError.prototype.toString = function() { }; function OperationalError(message) { - this.name = "OperationalError"; - this.message = message; + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { - this.message = message.message; - this.stack = message.stack; + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } @@ -118,8 +87,7 @@ function OperationalError(message) { } inherits(OperationalError, Error); -var key = "__BluebirdErrorTypes__"; -var errorTypes = Error[key]; +var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, @@ -128,7 +96,7 @@ if (!errorTypes) { RejectionError: OperationalError, AggregateError: AggregateError }); - notEnumerableProp(Error, key, errorTypes); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); } module.exports = { @@ -139,7 +107,5 @@ module.exports = { OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - canAttach: canAttach + Warning: Warning }; diff --git a/node_modules/bluebird/js/main/es5.js b/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/bluebird/js/main/es5.js @@ -0,0 +1,80 @@ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } + }; +} else { + var has = {}.hasOwnProperty; + var str = {}.toString; + var proto = {}.constructor.prototype; + + var ObjectKeys = function (o) { + var ret = []; + for (var key in o) { + if (has.call(o, key)) { + ret.push(key); + } + } + return ret; + }; + + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { + o[key] = desc.value; + return o; + }; + + var ObjectFreeze = function (obj) { + return obj; + }; + + var ObjectGetPrototypeOf = function (obj) { + try { + return Object(obj).constructor.prototype; + } + catch (e) { + return proto; + } + }; + + var ArrayIsArray = function (obj) { + try { + return str.call(obj) === "[object Array]"; + } + catch(e) { + return false; + } + }; + + module.exports = { + isArray: ArrayIsArray, + keys: ObjectKeys, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} diff --git a/node_modules/bluebird/js/main/filter.js b/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/bluebird/js/main/filter.js @@ -0,0 +1,12 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; + +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; + +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; diff --git a/node_modules/bluebird/js/main/finally.js b/node_modules/bluebird/js/main/finally.js new file mode 100644 index 0000000..c9342bc --- /dev/null +++ b/node_modules/bluebird/js/main/finally.js @@ -0,0 +1,98 @@ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = require("./util.js"); +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; + +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; + }; +} +function throw$(r) { + return function() { + throw r; + }; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} + +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundValue()) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } + } + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; + } +} + +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundValue(), value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); + } + } + return value; +} + +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); + + var promiseAndHandler = { + promise: this, + handler: handler + }; + + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; + +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; diff --git a/node_modules/bluebird/js/main/generators.js b/node_modules/bluebird/js/main/generators.js new file mode 100644 index 0000000..4c0568d --- /dev/null +++ b/node_modules/bluebird/js/main/generators.js @@ -0,0 +1,136 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = require("./errors.js"); +var TypeError = errors.TypeError; +var util = require("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/node_modules/bluebird/js/main/join.js b/node_modules/bluebird/js/main/join.js new file mode 100644 index 0000000..cf33eb1 --- /dev/null +++ b/node_modules/bluebird/js/main/join.js @@ -0,0 +1,107 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!false) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (reason) { + this._reject(reason); + }; +} +} + +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!false) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/map.js b/node_modules/bluebird/js/main/map.js similarity index 53% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/map.js rename to node_modules/bluebird/js/main/map.js index ecc9247..2f40efd 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/map.js +++ b/node_modules/bluebird/js/main/map.js @@ -1,53 +1,37 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ "use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, cast, INTERNAL) { +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = require("./async.js"); var util = require("./util.js"); -var tryCatch3 = util.tryCatch3; +var tryCatch = util.tryCatch; var errorObj = util.errorObj; var PENDING = {}; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); - this._callback = fn; + this._promise._captureStackTrace(); + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; - this._init$(void 0, -2); + async.invoke(init, this, undefined); } util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} -MappingPromiseArray.prototype._init = function MappingPromiseArray$_init() {}; +MappingPromiseArray.prototype._init = function () {}; -MappingPromiseArray.prototype._promiseFulfilled = -function MappingPromiseArray$_promiseFulfilled(value, index) { +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; - if (values === null) return; - var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; @@ -67,21 +51,23 @@ function MappingPromiseArray$_promiseFulfilled(value, index) { if (preservedValues !== null) preservedValues[index] = value; var callback = this._callback; - var receiver = this._promise._boundTo; - var ret = tryCatch3(callback, receiver, value, index, length); + var receiver = this._promise._boundValue(); + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); if (ret === errorObj) return this._reject(ret.e); - var maybePromise = cast(ret, void 0); + var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { if (limit >= 1) this._inFlight++; values[index] = PENDING; return maybePromise._proxyPromiseArray(this, index); - } else if (maybePromise.isFulfilled()) { - ret = maybePromise.value(); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); } else { - maybePromise._unsetRejectionIsUnhandled(); - return this._reject(maybePromise.reason()); + return this._reject(maybePromise._reason()); } } values[index] = ret; @@ -97,19 +83,18 @@ function MappingPromiseArray$_promiseFulfilled(value, index) { } }; -MappingPromiseArray.prototype._drainQueue = -function MappingPromiseArray$_drainQueue() { +MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; -MappingPromiseArray.prototype._filter = -function MappingPromiseArray$_filter(booleans, values) { +MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; @@ -120,8 +105,7 @@ function MappingPromiseArray$_filter(booleans, values) { this._resolve(ret); }; -MappingPromiseArray.prototype.preservedValues = -function MappingPromiseArray$preserveValues() { +MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; @@ -134,14 +118,14 @@ function map(promises, fn, options, _filter) { return new MappingPromiseArray(promises, fn, limit, _filter); } -Promise.prototype.map = function Promise$map(fn, options) { - if (typeof fn !== "function") return apiRejection("fn must be a function"); +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); return map(this, fn, options, null).promise(); }; -Promise.map = function Promise$Map(promises, fn, options, _filter) { - if (typeof fn !== "function") return apiRejection("fn must be a function"); +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); return map(promises, fn, options, _filter).promise(); }; diff --git a/node_modules/bluebird/js/main/method.js b/node_modules/bluebird/js/main/method.js new file mode 100644 index 0000000..3d3eeb1 --- /dev/null +++ b/node_modules/bluebird/js/main/method.js @@ -0,0 +1,44 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/node_modules/bluebird/js/main/nodeify.js b/node_modules/bluebird/js/main/nodeify.js new file mode 100644 index 0000000..257565d --- /dev/null +++ b/node_modules/bluebird/js/main/nodeify.js @@ -0,0 +1,59 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; + } + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; +}; diff --git a/node_modules/bluebird/js/main/progress.js b/node_modules/bluebird/js/main/progress.js new file mode 100644 index 0000000..2e3e95e --- /dev/null +++ b/node_modules/bluebird/js/main/progress.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = require("./util.js"); +var async = require("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; + +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); + +}; + +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; + +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } +}; + + +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } + } +}; +}; diff --git a/node_modules/bluebird/js/main/promise.js b/node_modules/bluebird/js/main/promise.js new file mode 100644 index 0000000..96bd545 --- /dev/null +++ b/node_modules/bluebird/js/main/promise.js @@ -0,0 +1,754 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; + +var util = require("./util.js"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var UNDEFINED_BINDING = {}; +var async = require("./async.js"); +var errors = require("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = require("./captured_trace.js")(); +var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + require("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = require("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function Promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); + } + if (this.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { + var len = arguments.length; + if (len > 1) { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (typeof item === "function") { + catchInstances[j++] = item; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + var catchFilter = new CatchFilter(catchInstances, fn, this); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); + } + return this._then(undefined, fn, undefined, undefined, undefined); +}; + +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject, didProgress) { + var promise = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); +}; + +Promise.prototype.isCancellable = function () { + return !this.isResolved() && + this._cancellable(); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = target._addCallbacks(didFulfill, + didReject, + didProgress, + ret, + receiver, + getDomain()); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { + return (this._bitField & 939524096) > 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 536870912) === 536870912; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 536870912; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 33554432) > 0; +}; + +Promise.prototype._cancellable = function () { + return (this._bitField & 67108864) > 0; +}; + +Promise.prototype._setCancellable = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._unsetCancellable = function () { + this._bitField = this._bitField & (~67108864); +}; + +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._boundValue = function() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, progress, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this._progressHandler0 = + domain === null ? progress : domain.bind(progress); + } + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this[base + 2] = + domain === null ? progress : domain.bind(progress); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; + } + this._setLength(index + 1); +}; + +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundValue(), value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; + } +}; + +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +Promise.prototype._fulfill = function (value) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._fulfillUnchecked(value); +}; + +Promise.prototype._reject = function (reason, carriedStackTrace) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._rejectUnchecked(reason, carriedStackTrace); +}; + +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } +}; + +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; +}; + +Promise.prototype._setSettlePromisesQueued = function () { + this._bitField = this._bitField | -1073741824; +}; + +Promise.prototype._unsetSettlePromisesQueued = function () { + this._bitField = this._bitField & (~-1073741824); +}; + +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err, undefined); + } + this._setFulfilled(); + this._settledValue = value; + this._cleanValues(); + + if (this._length() > 0) { + this._queueSettlePromises(); + } +}; + +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +require("./progress.js")(Promise, PromiseArray); +require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +require("./direct_resolve.js")(Promise); +require("./synchronous_inspection.js")(Promise); +require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./cancel.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +require('./nodeify.js')(Promise); +require('./call_get.js')(Promise); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +require('./settle.js')(Promise, PromiseArray); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./timers.js')(Promise, INTERNAL); +require('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/node_modules/bluebird/js/main/promise_array.js b/node_modules/bluebird/js/main/promise_array.js new file mode 100644 index 0000000..b2e8f1c --- /dev/null +++ b/node_modules/bluebird/js/main/promise_array.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = require("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +PromiseArray.prototype.length = function () { + return this._length; +}; + +PromiseArray.prototype.promise = function () { + return this._promise; +}; + +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + if (!isArray(values)) { + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + this.__hardReject__(err); + return; + } + } else if (values._isPending()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; + for (var i = 0; i < len; ++i) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._ignoreRejections(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/node_modules/bluebird/js/main/promise_resolver.js b/node_modules/bluebird/js/main/promise_resolver.js new file mode 100644 index 0000000..b180a32 --- /dev/null +++ b/node_modules/bluebird/js/main/promise_resolver.js @@ -0,0 +1,123 @@ +"use strict"; +var util = require("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = require("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise) { + return function(err, value) { + if (promise === null) return; + + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); + } + + promise = null; + }; +} + + +var PromiseResolver; +if (!haveGetters) { + PromiseResolver = function (promise) { + this.promise = promise; + this.asCallback = nodebackForPromise(promise); + this.callback = this.asCallback; + }; +} +else { + PromiseResolver = function (promise) { + this.promise = promise; + }; +} +if (haveGetters) { + var prop = { + get: function() { + return nodebackForPromise(this.promise); + } + }; + es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); + es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} + +PromiseResolver._nodebackForPromise = nodebackForPromise; + +PromiseResolver.prototype.toString = function () { + return "[object PromiseResolver]"; +}; + +PromiseResolver.prototype.resolve = +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._resolveCallback(value); +}; + +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._rejectCallback(reason); +}; + +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +PromiseResolver.prototype.timeout = function () { + this.reject(new TimeoutError("timeout")); +}; + +PromiseResolver.prototype.isResolved = function () { + return this.promise.isResolved(); +}; + +PromiseResolver.prototype.toJSON = function () { + return this.promise.toJSON(); +}; + +module.exports = PromiseResolver; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js b/node_modules/bluebird/js/main/promisify.js similarity index 50% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js rename to node_modules/bluebird/js/main/promisify.js index 933e0cf..86763d6 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promisify.js +++ b/node_modules/bluebird/js/main/promisify.js @@ -1,25 +1,3 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; @@ -31,16 +9,26 @@ var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = require("./errors").TypeError; var defaultSuffix = "Async"; -var defaultFilter = function(name, func) { +var defaultPromisified = {__isPromisified__: true}; +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && - !util.isClass(func); + name !== "constructor"; }; -var defaultPromisified = {__isPromisified__: true}; - -function escapeIdentRegex(str) { - return str.replace(/([$])/, "\\$"); +function propsFilter(key) { + return !noCopyPropsPattern.test(key); } function isPromisified(fn) { @@ -64,8 +52,8 @@ function checkValid(ret, suffix, suffixRegexp) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API " + - "that has normal methods with '"+suffix+"'-suffix"); + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); } } } @@ -78,10 +66,12 @@ function promisifiableMethods(obj, suffix, suffixRegexp, filter) { for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && - filter(key, value, obj)) { + filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } @@ -89,98 +79,66 @@ function promisifiableMethods(obj, suffix, suffixRegexp, filter) { return ret; } -function switchCaseArgumentOrder(likelyArgumentCount) { +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!false) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 5); + var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { - if (i === likelyArgumentCount) continue; ret.push(i); } - for(var i = likelyArgumentCount + 1; i <= 5; ++i) { + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; -} +}; -function argumentSequence(argumentCount) { - return util.filledRange(argumentCount, "arguments[", "]"); -} +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; -function parameterDeclaration(parameterCount) { - return util.filledRange(parameterCount, "_arg", ""); -} +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; -function parameterCount(fn) { +var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; -} - -function generatePropertyAccess(key) { - if (util.isIdentifier(key)) { - return "." + key; - } - else return "['" + key.replace(/(['\\])/g, "\\$1") + "']"; -} +}; -function makeNodePromisifiedEval(callback, receiver, originalName, fn, suffix) { +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var callbackName = - (typeof originalName === "string" && util.isIdentifier(originalName) - ? originalName + suffix - : "promisified"); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; - if (typeof callback === "string") { - ret = " \n\ - this.method(args, fn); \n\ - break; \n\ - ".replace(".method", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - ret = " \n\ - callback.call(this, args, fn); \n\ - break; \n\ - "; - } else if (receiver !== void 0) { - ret = " \n\ - callback.call(receiver, args, fn); \n\ - break; \n\ - "; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { - ret = " \n\ - callback(args, fn); \n\ - break; \n\ - "; + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } - return ret.replace("args", args).replace(", ", comma); + return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; - for(var i = 0; i < argumentOrder.length; ++i) { + for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } - var codeForCall; - if (typeof callback === "string") { - codeForCall = " \n\ - this.property.apply(this, args); \n\ - " - .replace(".property", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - codeForCall = " \n\ - callback.apply(this, args); \n\ - "; - } else { - codeForCall = " \n\ - callback.apply(receiver, args); \n\ - "; - } ret += " \n\ default: \n\ @@ -189,73 +147,87 @@ function makeNodePromisifiedEval(callback, receiver, originalName, fn, suffix) { for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ - args[i] = fn; \n\ + args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ - ".replace("[CodeForCall]", codeForCall); + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); return ret; } + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + return new Function("Promise", - "callback", + "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", - "INTERNAL"," \n\ - var ret = function FunctionName(Parameters) { \n\ + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ - promise._setTrace(void 0); \n\ - var fn = nodebackForPromise(promise); \n\ - try { \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - } catch (e) { \n\ - var wrapped = maybeWrapAsError(e); \n\ - promise._attachExtraTrace(wrapped); \n\ - promise._reject(wrapped); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ return promise; \n\ }; \n\ - ret.__isPromisified__ = true; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ " - .replace("FunctionName", callbackName) .replace("Parameters", parameterDeclaration(newParameterCount)) - .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()))( + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( Promise, - callback, + fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, INTERNAL ); +}; } -function makeNodePromisifiedClosure(callback, receiver) { +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; - if (typeof callback === "string") { - callback = _receiver[callback]; - } var promise = new Promise(INTERNAL); - promise._setTrace(void 0); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; var fn = nodebackForPromise(promise); try { - callback.apply(_receiver, withAppended(arguments, fn)); + cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { - var wrapped = maybeWrapAsError(e); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); + promise._rejectCallback(maybeWrapAsError(e), true, true); } return promise; } - promisified.__isPromisified__ = true; + util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } @@ -272,31 +244,40 @@ function promisifyAll(obj, suffix, filter, promisifier) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; - obj[promisifiedKey] = promisifier === makeNodePromisified - ? makeNodePromisified(key, THIS, key, fn, suffix) - : promisifier(fn); + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver) { - return makeNodePromisified(callback, receiver, void 0, callback); + return makeNodePromisified(callback, receiver, undefined, callback); } -Promise.promisify = function Promise$Promisify(fn, receiver) { +Promise.promisify = function (fn, receiver) { if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); } if (isPromisified(fn)) { return fn; } - return promisify(fn, arguments.length < 2 ? THIS : receiver); + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; }; -Promise.promisifyAll = function Promise$PromisifyAll(target, options) { +Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function"); + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); } options = Object(options); var suffix = options.suffix; @@ -307,10 +288,10 @@ Promise.promisifyAll = function Promise$PromisifyAll(target, options) { if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier"); + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); } - var keys = util.inheritedDataKeys(target, {includeHidden: true}); + var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && diff --git a/node_modules/bluebird/js/main/props.js b/node_modules/bluebird/js/main/props.js new file mode 100644 index 0000000..d6f9e64 --- /dev/null +++ b/node_modules/bluebird/js/main/props.js @@ -0,0 +1,79 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util.js"); +var isObject = util.isObject; +var es5 = require("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; +}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val = {}; + var keyOffset = this.length(); + for (var i = 0, len = this.length(); i < len; ++i) { + val[this._values[i + keyOffset]] = this._values[i]; + } + this._resolve(val); + } +}; + +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { + this._promise._progress({ + key: this._values[index + this.length()], + value: value + }); +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } + + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/node_modules/bluebird/js/main/queue.js b/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/node_modules/bluebird/js/main/queue.js @@ -0,0 +1,90 @@ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +Queue.prototype._willBeOverCapacity = function (size) { + return this._capacity < size; +}; + +Queue.prototype._pushOne = function (arg) { + var length = this.length(); + this._checkCapacity(length + 1); + var i = (this._front + length) & (this._capacity - 1); + this[i] = arg; + this._length = length + 1; +}; + +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { + var length = this.length() + 3; + if (this._willBeOverCapacity(length)) { + this._pushOne(fn); + this._pushOne(receiver); + this._pushOne(arg); + return; + } + var j = this._front + length - 3; + this._checkCapacity(length); + var wrapMask = this._capacity - 1; + this[(j + 0) & wrapMask] = fn; + this[(j + 1) & wrapMask] = receiver; + this[(j + 2) & wrapMask] = arg; + this._length = length; +}; + +Queue.prototype.shift = function () { + var front = this._front, + ret = this[front]; + + this[front] = undefined; + this._front = (front + 1) & (this._capacity - 1); + this._length--; + return ret; +}; + +Queue.prototype.length = function () { + return this._length; +}; + +Queue.prototype._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; diff --git a/node_modules/bluebird/js/main/race.js b/node_modules/bluebird/js/main/race.js new file mode 100644 index 0000000..30e7bb0 --- /dev/null +++ b/node_modules/bluebird/js/main/race.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = require("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; + + if (val === undefined && !(i in promises)) { + continue; + } + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); + } + return ret; +} + +Promise.race = function (promises) { + return race(promises, undefined); +}; + +Promise.prototype.race = function () { + return race(this, undefined); +}; + +}; diff --git a/node_modules/bluebird/js/main/reduce.js b/node_modules/bluebird/js/main/reduce.js new file mode 100644 index 0000000..1f92daf --- /dev/null +++ b/node_modules/bluebird/js/main/reduce.js @@ -0,0 +1,148 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = require("./async.js"); +var util = require("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._init = function () {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); + } +}; + +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 134217728; + ret._settledValue = reason; + this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; +}; diff --git a/node_modules/bluebird/js/main/some.js b/node_modules/bluebird/js/main/some.js new file mode 100644 index 0000000..f3968cf --- /dev/null +++ b/node_modules/bluebird/js/main/some.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util.js"); +var RangeError = require("./errors.js").RangeError; +var AggregateError = require("./errors.js").AggregateError; +var isArray = util.isArray; + + +function SomePromiseArray(values) { + this.constructor$(values); + this._howMany = 0; + this._unwrap = false; + this._initialized = false; +} +util.inherits(SomePromiseArray, PromiseArray); + +SomePromiseArray.prototype._init = function () { + if (!this._initialized) { + return; + } + if (this._howMany === 0) { + this._resolve([]); + return; + } + this._init$(undefined, -5); + var isArrayResolved = isArray(this._values); + if (!this._isResolved() && + isArrayResolved && + this._howMany > this._canPossiblyFulfill()) { + this._reject(this._getRangeError(this.length())); + } +}; + +SomePromiseArray.prototype.init = function () { + this._initialized = true; + this._init(); +}; + +SomePromiseArray.prototype.setUnwrap = function () { + this._unwrap = true; +}; + +SomePromiseArray.prototype.howMany = function () { + return this._howMany; +}; + +SomePromiseArray.prototype.setHowMany = function (count) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + this._addFulfilled(value); + if (this._fulfilled() === this.howMany()) { + this._values.length = this.howMany(); + if (this.howMany() === 1 && this._unwrap) { + this._resolve(this._values[0]); + } else { + this._resolve(this._values); + } + } + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); + } + this._reject(e); + } +}; + +SomePromiseArray.prototype._fulfilled = function () { + return this._totalResolved; +}; + +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); +}; + +SomePromiseArray.prototype._addRejected = function (reason) { + this._values.push(reason); +}; + +SomePromiseArray.prototype._addFulfilled = function (value) { + this._values[this._totalResolved++] = value; +}; + +SomePromiseArray.prototype._canPossiblyFulfill = function () { + return this.length() - this._rejected(); +}; + +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); +}; + +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; diff --git a/node_modules/bluebird/js/main/synchronous_inspection.js b/node_modules/bluebird/js/main/synchronous_inspection.js new file mode 100644 index 0000000..7aac149 --- /dev/null +++ b/node_modules/bluebird/js/main/synchronous_inspection.js @@ -0,0 +1,94 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/node_modules/bluebird/js/main/thenables.js b/node_modules/bluebird/js/main/thenables.js new file mode 100644 index 0000000..eadfffb --- /dev/null +++ b/node_modules/bluebird/js/main/thenables.js @@ -0,0 +1,84 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/node_modules/bluebird/js/main/timers.js b/node_modules/bluebird/js/main/timers.js new file mode 100644 index 0000000..f26431a --- /dev/null +++ b/node_modules/bluebird/js/main/timers.js @@ -0,0 +1,64 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + + var err; + if(!util.isPrimitive(message) && (message instanceof Error)) { + err = message; + } else { + if (typeof message !== "string") { + message = "operation timed out"; + } + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/using.js b/node_modules/bluebird/js/main/using.js similarity index 58% rename from node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/using.js rename to node_modules/bluebird/js/main/using.js index 9ade965..957182d 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/using.js +++ b/node_modules/bluebird/js/main/using.js @@ -1,27 +1,6 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ "use strict"; -module.exports = function (Promise, apiRejection, cast) { +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { var TypeError = require("./errors.js").TypeError; var inherits = require("./util.js").inherits; var PromiseInspection = Promise.PromiseInspection; @@ -33,7 +12,7 @@ module.exports = function (Promise, apiRejection, cast) { if (inspection.isRejected()) { return Promise.reject(inspection.error()); } - inspections[i] = inspection.value(); + inspections[i] = inspection._settledValue; } return inspections; } @@ -43,7 +22,7 @@ module.exports = function (Promise, apiRejection, cast) { } function castPreservingDisposable(thenable) { - var maybePromise = cast(thenable, void 0); + var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && @@ -62,8 +41,9 @@ module.exports = function (Promise, apiRejection, cast) { if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { - maybePromise = cast(maybePromise._getDisposer() - .tryDispose(inspection), void 0); + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); } catch (e) { return thrower(e); } @@ -92,20 +72,21 @@ module.exports = function (Promise, apiRejection, cast) { return dispose(this, inspection).thenThrow(reason); } - function Disposer(data, promise) { + function Disposer(data, promise, context) { this._data = data; this._promise = promise; + this._context = context; } - Disposer.prototype.data = function Disposer$data() { + Disposer.prototype.data = function () { return this._data; }; - Disposer.prototype.promise = function Disposer$promise() { + Disposer.prototype.promise = function () { return this._promise; }; - Disposer.prototype.resource = function Disposer$resource() { + Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } @@ -114,21 +95,24 @@ module.exports = function (Promise, apiRejection, cast) { Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); var ret = resource !== null ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); - this._data = this._promise = null; + this._data = null; return ret; }; - Disposer.isDisposer = function Disposer$isDisposer(d) { + Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; - function FunctionDisposer(fn, promise) { - this.constructor$(fn, promise); + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); @@ -137,52 +121,91 @@ module.exports = function (Promise, apiRejection, cast) { return fn.call(resource, resource, inspection); }; - Promise.using = function Promise$using() { + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; - if (typeof fn !== "function") return apiRejection("fn must be a function"); - len--; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } var resources = new Array(len); for (var i = 0; i < len; ++i) { - var resource = arguments[i]; + var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } } resources[i] = resource; } - return Promise.settle(resources) + var promise = Promise.settle(resources) .then(inspectionMapper) - .spread(fn) - ._then(disposerSuccess, disposerFail, void 0, resources, void 0); + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = spreadArgs + ? fn.apply(undefined, vals) : fn.call(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; }; - Promise.prototype._setDisposable = - function Promise$_setDisposable(disposer) { + Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 262144; this._disposer = disposer; }; - Promise.prototype._isDisposable = function Promise$_isDisposable() { + Promise.prototype._isDisposable = function () { return (this._bitField & 262144) > 0; }; - Promise.prototype._getDisposer = function Promise$_getDisposer() { + Promise.prototype._getDisposer = function () { return this._disposer; }; - Promise.prototype._unsetDisposable = function Promise$_unsetDisposable() { + Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~262144); - this._disposer = void 0; + this._disposer = undefined; }; - Promise.prototype.disposer = function Promise$disposer(fn) { + Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { - return new FunctionDisposer(fn, this); + return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; diff --git a/node_modules/bluebird/js/main/util.js b/node_modules/bluebird/js/main/util.js new file mode 100644 index 0000000..ea39344 --- /dev/null +++ b/node_modules/bluebird/js/main/util.js @@ -0,0 +1,321 @@ +"use strict"; +var es5 = require("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +var inherits = function(Child, Parent) { + var hasProp = {}.hasOwnProperty; + + function T() { + this.constructor = Child; + this.constructor$ = Parent; + for (var propertyName in Parent.prototype) { + if (hasProp.call(Parent.prototype, propertyName) && + propertyName.charAt(propertyName.length-1) !== "$" + ) { + this[propertyName + "$"] = Parent.prototype[propertyName]; + } + } + } + T.prototype = Parent.prototype; + Child.prototype = new T(); + return Child.prototype; +}; + + +function isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return !isPrimitive(value); +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(maybeError)); +} + +function withAppended(target, appendee) { + var len = target.length; + var ret = new Array(len + 1); + var i; + for (i = 0; i < len; ++i) { + ret[i] = target[i]; + } + ret[i] = appendee; + return ret; +} + +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} + +function notEnumerableProp(obj, name, value) { + if (isPrimitive(obj)) return obj; + var descriptor = { + value: value, + configurable: true, + enumerable: false, + writable: true + }; + es5.defineProperty(obj, name, descriptor); + return obj; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + eval(obj); +} + +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + haveGetters: haveGetters, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json new file mode 100644 index 0000000..2654c72 --- /dev/null +++ b/node_modules/bluebird/package.json @@ -0,0 +1,103 @@ +{ + "_from": "bluebird@2.10.2", + "_id": "bluebird@2.10.2", + "_inBundle": false, + "_integrity": "sha1-AkpVFylTCIV/FPkfEQb8O1VfRGs=", + "_location": "/bluebird", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "bluebird@2.10.2", + "name": "bluebird", + "escapedName": "bluebird", + "rawSpec": "2.10.2", + "saveSpec": null, + "fetchSpec": "2.10.2" + }, + "_requiredBy": [ + "/mquery" + ], + "_resolved": "http://registry.npmjs.org/bluebird/-/bluebird-2.10.2.tgz", + "_shasum": "024a5517295308857f14f91f1106fc3b555f446b", + "_spec": "bluebird@2.10.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mquery", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "browser": "./js/browser/bluebird.js", + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "kefir": "^2.4.1", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "zalgo.js" + ], + "homepage": "https://github.com/petkaantonov/bluebird", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface", + "parallel", + "thread", + "concurrency" + ], + "license": "MIT", + "main": "./js/main/bluebird.js", + "name": "bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "scripts": { + "generate-browser-core": "node tools/build.js --features=core --no-debug --main --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", + "istanbul": "istanbul", + "lint": "node scripts/jshint.js", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify", + "test": "node tools/test.js" + }, + "version": "2.10.2" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/.travis.yml b/node_modules/bson/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/.travis.yml rename to node_modules/bson/.travis.yml diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/HISTORY b/node_modules/bson/HISTORY similarity index 90% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/HISTORY rename to node_modules/bson/HISTORY index 5450c14..4f422b0 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/HISTORY +++ b/node_modules/bson/HISTORY @@ -1,3 +1,7 @@ +0.2.22 2015-07-23 +----------------- +- Updated Nan to 1.8.x to support io.js and node 0.12.0 + 0.2.21 2015-03-21 ----------------- - Updated Nan to 1.7.0 to support io.js and node 0.12.0 diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE b/node_modules/bson/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/LICENSE rename to node_modules/bson/LICENSE diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/Makefile b/node_modules/bson/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/Makefile rename to node_modules/bson/Makefile diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/README.md b/node_modules/bson/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/README.md rename to node_modules/bson/README.md diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/bson/binding.gyp similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/binding.gyp rename to node_modules/bson/binding.gyp diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/bson.js b/node_modules/bson/browser_build/bson.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/bson.js rename to node_modules/bson/browser_build/bson.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/bson/browser_build/package.json similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/browser_build/package.json rename to node_modules/bson/browser_build/package.json diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build_browser.js b/node_modules/bson/build_browser.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/build_browser.js rename to node_modules/bson/build_browser.js diff --git a/node_modules/bson/builderror.log b/node_modules/bson/builderror.log new file mode 100644 index 0000000..9b62dcf --- /dev/null +++ b/node_modules/bson/builderror.log @@ -0,0 +1,12 @@ +gyp ERR! configure error +gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable. +gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:484:19) +gyp ERR! stack at PythonFinder. (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:509:16) +gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29 +gyp ERR! stack at FSReqWrap.oncomplete (fs.js:152:21) +gyp ERR! System Windows_NT 10.0.16299 +gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" +gyp ERR! cwd E:\github\node-dc-mongo\node_modules\bson +gyp ERR! node -v v8.12.0 +gyp ERR! node-gyp -v v3.8.0 +gyp ERR! not ok diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/Makefile b/node_modules/bson/ext/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/Makefile rename to node_modules/bson/ext/Makefile diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.cc b/node_modules/bson/ext/bson.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.cc rename to node_modules/bson/ext/bson.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.h b/node_modules/bson/ext/bson.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/bson.h rename to node_modules/bson/ext/bson.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js b/node_modules/bson/ext/index.js similarity index 88% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js rename to node_modules/bson/ext/index.js index 0d3cd35..5550fcf 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js +++ b/node_modules/bson/ext/index.js @@ -3,16 +3,16 @@ var bson = null; try { // Load the precompiled win32 binary if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); + bson = require('./win32/x64/bson'); } else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); + bson = require('./win32/ia32/bson'); } else { - bson = require('../build/Release/bson'); - } + bson = require('bson'); + } } catch(err) { // Attempt to load the release bson version try { - bson = require('../build/Release/bson'); + bson = require('bson'); } catch (err) { console.dir(err) console.error("js-bson: Failed to load c++ bson extension, using pure JS version"); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/bson/ext/win32/ia32/bson.node similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node rename to node_modules/bson/ext/win32/ia32/bson.node diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/node_modules/bson/ext/win32/x64/bson.node similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node rename to node_modules/bson/ext/win32/x64/bson.node diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/wscript b/node_modules/bson/ext/wscript similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/wscript rename to node_modules/bson/ext/wscript diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/node_modules/bson/lib/bson/binary.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary.js rename to node_modules/bson/lib/bson/binary.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/node_modules/bson/lib/bson/binary_parser.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js rename to node_modules/bson/lib/bson/binary_parser.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/node_modules/bson/lib/bson/bson.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson.js rename to node_modules/bson/lib/bson/bson.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson_new.js b/node_modules/bson/lib/bson/bson_new.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/bson_new.js rename to node_modules/bson/lib/bson/bson_new.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/node_modules/bson/lib/bson/code.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/code.js rename to node_modules/bson/lib/bson/code.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/node_modules/bson/lib/bson/db_ref.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js rename to node_modules/bson/lib/bson/db_ref.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/node_modules/bson/lib/bson/double.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/double.js rename to node_modules/bson/lib/bson/double.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/node_modules/bson/lib/bson/float_parser.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js rename to node_modules/bson/lib/bson/float_parser.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/node_modules/bson/lib/bson/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/index.js rename to node_modules/bson/lib/bson/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/node_modules/bson/lib/bson/long.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/long.js rename to node_modules/bson/lib/bson/long.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/node_modules/bson/lib/bson/max_key.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js rename to node_modules/bson/lib/bson/max_key.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/node_modules/bson/lib/bson/min_key.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js rename to node_modules/bson/lib/bson/min_key.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/node_modules/bson/lib/bson/objectid.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js rename to node_modules/bson/lib/bson/objectid.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/node_modules/bson/lib/bson/symbol.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js rename to node_modules/bson/lib/bson/symbol.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/node_modules/bson/lib/bson/timestamp.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js rename to node_modules/bson/lib/bson/timestamp.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json b/node_modules/bson/package.json similarity index 57% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json rename to node_modules/bson/package.json index 4caabf9..d1e13ed 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/package.json +++ b/node_modules/bson/package.json @@ -1,77 +1,77 @@ { - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" + "_from": "bson@~0.2", + "_id": "bson@0.2.22", + "_inBundle": false, + "_integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", + "_location": "/bson", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bson@~0.2", + "name": "bson", + "escapedName": "bson", + "rawSpec": "~0.2", + "saveSpec": null, + "fetchSpec": "~0.2" + }, + "_requiredBy": [ + "/mongodb" ], - "version": "0.2.21", + "_resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", + "_shasum": "fcda103f26d0c074d5a52d50927db80fd02b4b39", + "_spec": "bson@~0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb", "author": { "name": "Christian Amor Kvalheim", "email": "christkv@gmail.com" }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, + "browser": "lib/bson/bson.js", "bugs": { "url": "https://github.com/mongodb/js-bson/issues" }, + "bundleDependencies": false, + "config": { + "native": false + }, + "contributors": [], "dependencies": { - "nan": "1.7.0" + "nan": "~1.8" }, + "deprecated": false, + "description": "A bson parser for node.js and the browser", "devDependencies": { - "nodeunit": "0.9.0", "gleak": "0.2.3", + "nodeunit": "0.9.0", "one": "2.X.X" }, - "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" - }, - "browser": "lib/bson/bson.js", + "homepage": "https://github.com/mongodb/js-bson#readme", + "keywords": [ + "mongodb", + "bson", + "parser" + ], "licenses": [ { "type": "Apache License, Version 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0" } ], - "gitHead": "a4b8ff14e3dcc92d144817a806f4c5ba536a7f2e", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.2.21", - "_shasum": "3755a5de71ac43f0e9a85f699c84d1ab73b0fcb3", - "_from": "bson@>=0.2.0 <0.3.0", - "_npmVersion": "2.7.1", - "_nodeVersion": "1.6.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" + "main": "./lib/bson/index", + "name": "bson", + "repository": { + "type": "git", + "url": "git://github.com/mongodb/js-bson.git" }, - "maintainers": [ - { - "name": "octave", - "email": "chinsay@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "3755a5de71ac43f0e9a85f699c84d1ab73b0fcb3", - "tarball": "http://registry.npmjs.org/bson/-/bson-0.2.21.tgz" + "scripts": { + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" }, - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.2.21.tgz" + "version": "0.2.22" } diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/gleak.js b/node_modules/bson/tools/gleak.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/gleak.js rename to node_modules/bson/tools/gleak.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE rename to node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js rename to node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/bson/tools/jasmine-1.1.0/jasmine.css similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css rename to node_modules/bson/tools/jasmine-1.1.0/jasmine.css diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/bson/tools/jasmine-1.1.0/jasmine.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js rename to node_modules/bson/tools/jasmine-1.1.0/jasmine.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png rename to node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png diff --git a/node_modules/debug/.jshintrc b/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/node_modules/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/node_modules/debug/History.md b/node_modules/debug/History.md new file mode 100644 index 0000000..854c971 --- /dev/null +++ b/node_modules/debug/History.md @@ -0,0 +1,195 @@ + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/debug/Makefile b/node_modules/debug/Makefile new file mode 100644 index 0000000..5cf4a59 --- /dev/null +++ b/node_modules/debug/Makefile @@ -0,0 +1,36 @@ + +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# applications +NODE ?= $(shell which node) +NPM ?= $(NODE) $(shell which npm) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +all: dist/debug.js + +install: node_modules + +clean: + @rm -rf dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +distclean: clean + @rm -rf node_modules + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean distclean diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/node_modules/debug/Readme.md similarity index 58% rename from node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md rename to node_modules/debug/Readme.md index c5a34e8..b4f45e3 100644 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md +++ b/node_modules/debug/Readme.md @@ -4,14 +4,14 @@ ## Installation -``` +```bash $ npm install debug ``` ## Usage With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - + Example _app.js_: ```js @@ -51,30 +51,51 @@ setInterval(function(){ ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + +Then, run the program to be debugged as usual. + ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_ - + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - + ## Conventions - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". ## Wildcards - The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Browser support - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + Debug works in the browser as well, currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. Somewhere in the code on your page, include: + +```js +window.myDebug = require("debug"); +``` + + ("debug" is a global object in the browser so we give this object a different name.) When your page is open in the browser, type the following in the console: + +```js +myDebug.enable("worker:*") +``` + + Refresh the page. Debug output will continue to be sent to the console until it is disabled by typing `myDebug.disable()` in the console. ```js a = debug('worker:a'); @@ -85,15 +106,67 @@ setInterval(function(){ }, 1000); setInterval(function(){ - a('doing some work'); + b('doing some work'); }, 1200); ``` -## License +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + +### stderr vs stdout + +You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +### Save debug output to a file + +You can save all debug statements to a file by piping them. + +Example: + +```bash +$ DEBUG_FD=3 node your-app.js 3> whatever.log +``` + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + +## License (The MIT License) -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/node_modules/debug/bower.json b/node_modules/debug/bower.json new file mode 100644 index 0000000..6af573f --- /dev/null +++ b/node_modules/debug/bower.json @@ -0,0 +1,28 @@ +{ + "name": "visionmedia-debug", + "main": "dist/debug.js", + "version": "2.2.0", + "homepage": "https://github.com/visionmedia/debug", + "authors": [ + "TJ Holowaychuk " + ], + "description": "visionmedia-debug", + "moduleType": [ + "amd", + "es6", + "globals", + "node" + ], + "keywords": [ + "visionmedia", + "debug" + ], + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/node_modules/debug/browser.js b/node_modules/debug/browser.js new file mode 100644 index 0000000..7c76452 --- /dev/null +++ b/node_modules/debug/browser.js @@ -0,0 +1,168 @@ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // is webkit? http://stackoverflow.com/a/16459606/376773 + return ('WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (window.console && (console.firebug || (console.exception && console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + return JSON.stringify(v); +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return args; + + var c = 'color: ' + this.color; + args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + return args; +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage(){ + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/debug/component.json b/node_modules/debug/component.json new file mode 100644 index 0000000..ca10637 --- /dev/null +++ b/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.2.0", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/debug/debug.js b/node_modules/debug/debug.js new file mode 100644 index 0000000..7571a86 --- /dev/null +++ b/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lowercased letter, i.e. "n". + */ + +exports.formatters = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function selectColor() { + return exports.colors[prevColor++ % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function debug(namespace) { + + // define the `disabled` version + function disabled() { + } + disabled.enabled = false; + + // define the `enabled` version + function enabled() { + + var self = enabled; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // add the `color` if not set + if (null == self.useColors) self.useColors = exports.useColors(); + if (null == self.color && self.useColors) self.color = selectColor(); + + var args = Array.prototype.slice.call(arguments); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %o + args = ['%o'].concat(args); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + if ('function' === typeof exports.formatArgs) { + args = exports.formatArgs.apply(self, args); + } + var logFn = enabled.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + enabled.enabled = true; + + var fn = exports.enabled(namespace) ? enabled : disabled; + + fn.namespace = namespace; + + return fn; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 0000000..1d392a8 --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1,209 @@ + +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); + if (0 === debugColors.length) { + return tty.isatty(fd); + } else { + return '0' !== debugColors + && 'no' !== debugColors + && 'false' !== debugColors + && 'disabled' !== debugColors; + } +} + +/** + * Map %o to `util.inspect()`, since Node doesn't do that out of the box. + */ + +var inspect = (4 === util.inspect.length ? + // node <= 0.8.x + function (v, colors) { + return util.inspect(v, void 0, void 0, colors); + } : + // node > 0.8.x + function (v, colors) { + return util.inspect(v, { colors: colors }); + } +); + +exports.formatters.o = function(v) { + return inspect(v, this.useColors) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + var name = this.namespace; + + if (useColors) { + var c = this.color; + + args[0] = ' \u001b[3' + c + ';1m' + name + ' ' + + '\u001b[0m' + + args[0] + '\u001b[3' + c + 'm' + + ' +' + exports.humanize(this.diff) + '\u001b[0m'; + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } + return args; +} + +/** + * Invokes `console.error()` with the specified arguments. + */ + +function log() { + return stream.write(util.format.apply(this, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/debug/node_modules/ms/.npmignore b/node_modules/debug/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/node_modules/debug/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/node_modules/debug/node_modules/ms/History.md b/node_modules/debug/node_modules/ms/History.md new file mode 100644 index 0000000..32fdfc1 --- /dev/null +++ b/node_modules/debug/node_modules/ms/History.md @@ -0,0 +1,66 @@ + +0.7.1 / 2015-04-20 +================== + + * prevent extraordinary long inputs (@evilpacket) + * Fixed broken readme link + +0.7.0 / 2014-11-24 +================== + + * add time abbreviations, updated tests and readme for the new units + * fix example in the readme. + * add LICENSE file + +0.6.2 / 2013-12-05 +================== + + * Adding repository section to package.json to suppress warning from NPM. + +0.6.1 / 2013-05-10 +================== + + * fix singularization [visionmedia] + +0.6.0 / 2013-03-15 +================== + + * fix minutes + +0.5.1 / 2013-02-24 +================== + + * add component namespace + +0.5.0 / 2012-11-09 +================== + + * add short formatting as default and .long option + * add .license property to component.json + * add version to component.json + +0.4.0 / 2012-10-22 +================== + + * add rounding to fix crazy decimals + +0.3.0 / 2012-09-07 +================== + + * fix `ms()` [visionmedia] + +0.2.0 / 2012-09-03 +================== + + * add component.json [visionmedia] + * add days support [visionmedia] + * add hours support [visionmedia] + * add minutes support [visionmedia] + * add seconds support [visionmedia] + * add ms string support [visionmedia] + * refactor tests to facilitate ms(number) [visionmedia] + +0.1.0 / 2012-03-07 +================== + + * Initial release diff --git a/node_modules/debug/node_modules/ms/LICENSE b/node_modules/debug/node_modules/ms/LICENSE new file mode 100644 index 0000000..6c07561 --- /dev/null +++ b/node_modules/debug/node_modules/ms/LICENSE @@ -0,0 +1,20 @@ +(The MIT License) + +Copyright (c) 2014 Guillermo Rauch + +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. diff --git a/node_modules/debug/node_modules/ms/README.md b/node_modules/debug/node_modules/ms/README.md new file mode 100644 index 0000000..9b4fd03 --- /dev/null +++ b/node_modules/debug/node_modules/ms/README.md @@ -0,0 +1,35 @@ +# ms.js: miliseconds conversion utility + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('100') // 100 +``` + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +- Node/Browser compatible. Published as [`ms`](https://www.npmjs.org/package/ms) in [NPM](http://nodejs.org/download). +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as +a number (e.g: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT diff --git a/node_modules/debug/node_modules/ms/index.js b/node_modules/debug/node_modules/ms/index.js new file mode 100644 index 0000000..4f92771 --- /dev/null +++ b/node_modules/debug/node_modules/ms/index.js @@ -0,0 +1,125 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/debug/node_modules/ms/package.json b/node_modules/debug/node_modules/ms/package.json new file mode 100644 index 0000000..6cc94d6 --- /dev/null +++ b/node_modules/debug/node_modules/ms/package.json @@ -0,0 +1,49 @@ +{ + "_from": "ms@0.7.1", + "_id": "ms@0.7.1", + "_inBundle": false, + "_integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=", + "_location": "/debug/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.7.1", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.7.1", + "saveSpec": null, + "fetchSpec": "0.7.1" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "_shasum": "9cd13c03adbff25b65effde7ce864ee952017098", + "_spec": "ms@0.7.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\debug", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "ms/index.js": "index.js" + } + }, + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" + }, + "homepage": "https://github.com/guille/ms.js#readme", + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git://github.com/guille/ms.js.git" + }, + "version": "0.7.1" +} diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..14daf70 --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,70 @@ +{ + "_from": "debug@2.2.0", + "_id": "debug@2.2.0", + "_inBundle": false, + "_integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@2.2.0", + "name": "debug", + "escapedName": "debug", + "rawSpec": "2.2.0", + "saveSpec": null, + "fetchSpec": "2.2.0" + }, + "_requiredBy": [ + "/mquery" + ], + "_resolved": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "_shasum": "f87057e995b1a1f6ae6a4960664137bc56f039da", + "_spec": "debug@2.2.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mquery", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "dependencies": { + "ms": "0.7.1" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "9.0.3", + "mocha": "*" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./node.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "2.2.0" +} diff --git a/node_modules/mongoose/node_modules/hooks/.npmignore b/node_modules/hooks/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/hooks/.npmignore rename to node_modules/hooks/.npmignore diff --git a/node_modules/mongoose/node_modules/hooks/Makefile b/node_modules/hooks/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/hooks/Makefile rename to node_modules/hooks/Makefile diff --git a/node_modules/mongoose/node_modules/hooks/README.md b/node_modules/hooks/README.md similarity index 100% rename from node_modules/mongoose/node_modules/hooks/README.md rename to node_modules/hooks/README.md diff --git a/node_modules/mongoose/node_modules/hooks/hooks.alt.js b/node_modules/hooks/hooks.alt.js similarity index 100% rename from node_modules/mongoose/node_modules/hooks/hooks.alt.js rename to node_modules/hooks/hooks.alt.js diff --git a/node_modules/mongoose/node_modules/hooks/hooks.js b/node_modules/hooks/hooks.js similarity index 100% rename from node_modules/mongoose/node_modules/hooks/hooks.js rename to node_modules/hooks/hooks.js diff --git a/node_modules/hooks/package.json b/node_modules/hooks/package.json new file mode 100644 index 0000000..73bc8f0 --- /dev/null +++ b/node_modules/hooks/package.json @@ -0,0 +1,88 @@ +{ + "_defaultsLoaded": true, + "_engineSupported": true, + "_from": "hooks@0.2.1", + "_id": "hooks@0.2.1", + "_inBundle": false, + "_integrity": "sha1-D1kbGzRL3LPfWXc/Yvu6+Fv0Aos=", + "_location": "/hooks", + "_nodeVersion": "v0.6.15", + "_npmUser": { + "name": "bnoguchi", + "email": "brian.noguchi@gmail.com" + }, + "_npmVersion": "1.1.16", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "hooks@0.2.1", + "name": "hooks", + "escapedName": "hooks", + "rawSpec": "0.2.1", + "saveSpec": null, + "fetchSpec": "0.2.1" + }, + "_requiredBy": [ + "/mongoose" + ], + "_resolved": "https://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz", + "_shasum": "0f591b1b344bdcb3df59773f62fbbaf85bf4028b", + "_spec": "hooks@0.2.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", + "author": { + "name": "Brian Noguchi", + "email": "brian.noguchi@gmail.com", + "url": "https://github.com/bnoguchi/" + }, + "bugs": { + "url": "https://github.com/bnoguchi/hooks-js/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Adds pre and post hook functionality to your JavaScript methods.", + "devDependencies": { + "expresso": ">=0.7.6", + "should": ">=0.2.1", + "underscore": ">=1.1.4" + }, + "directories": { + "lib": "." + }, + "dist": { + "shasum": "0f591b1b344bdcb3df59773f62fbbaf85bf4028b", + "tarball": "http://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz" + }, + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/bnoguchi/hooks-js/", + "keywords": [ + "node", + "hooks", + "middleware", + "pre", + "post" + ], + "licenses": [ + "MIT" + ], + "main": "./hooks.js", + "maintainers": [ + { + "name": "bnoguchi", + "email": "brian.noguchi@gmail.com" + } + ], + "name": "hooks", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/bnoguchi/hooks-js.git" + }, + "scripts": { + "test": "make test" + }, + "version": "0.2.1" +} diff --git a/node_modules/mongoose/node_modules/hooks/test.js b/node_modules/hooks/test.js similarity index 100% rename from node_modules/mongoose/node_modules/hooks/test.js rename to node_modules/hooks/test.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE rename to node_modules/inherits/LICENSE diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/node_modules/inherits/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md rename to node_modules/inherits/README.md diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..3b94763 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js rename to node_modules/inherits/inherits_browser.js diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..227febb --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@^2.0.3", + "_id": "inherits@2.0.3", + "_inBundle": false, + "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@^2.0.3", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "^2.0.3", + "saveSpec": null, + "fetchSpec": "^2.0.3" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "_shasum": "633c2c83e3da42a502f52466022480f4208261de", + "_spec": "inherits@^2.0.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\readable-stream", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "node test" + }, + "version": "2.0.3" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/LICENSE b/node_modules/kerberos/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/LICENSE rename to node_modules/kerberos/LICENSE diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md b/node_modules/kerberos/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md rename to node_modules/kerberos/README.md diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp b/node_modules/kerberos/binding.gyp similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp rename to node_modules/kerberos/binding.gyp diff --git a/node_modules/kerberos/builderror.log b/node_modules/kerberos/builderror.log new file mode 100644 index 0000000..31011d0 --- /dev/null +++ b/node_modules/kerberos/builderror.log @@ -0,0 +1,12 @@ +gyp ERR! configure error +gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable. +gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:484:19) +gyp ERR! stack at PythonFinder. (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:509:16) +gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29 +gyp ERR! stack at FSReqWrap.oncomplete (fs.js:152:21) +gyp ERR! System Windows_NT 10.0.16299 +gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" +gyp ERR! cwd E:\github\node-dc-mongo\node_modules\kerberos +gyp ERR! node -v v8.12.0 +gyp ERR! node-gyp -v v3.8.0 +gyp ERR! not ok diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js b/node_modules/kerberos/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js rename to node_modules/kerberos/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/kerberos/lib/auth_processes/mongodb.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js rename to node_modules/kerberos/lib/auth_processes/mongodb.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/node_modules/kerberos/lib/base64.c similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c rename to node_modules/kerberos/lib/base64.c diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/node_modules/kerberos/lib/base64.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h rename to node_modules/kerberos/lib/base64.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/node_modules/kerberos/lib/kerberos.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc rename to node_modules/kerberos/lib/kerberos.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/node_modules/kerberos/lib/kerberos.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h rename to node_modules/kerberos/lib/kerberos.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/node_modules/kerberos/lib/kerberos.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js rename to node_modules/kerberos/lib/kerberos.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/kerberos/lib/kerberos_context.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc rename to node_modules/kerberos/lib/kerberos_context.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/node_modules/kerberos/lib/kerberos_context.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h rename to node_modules/kerberos/lib/kerberos_context.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/node_modules/kerberos/lib/kerberosgss.c similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c rename to node_modules/kerberos/lib/kerberosgss.c diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/node_modules/kerberos/lib/kerberosgss.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h rename to node_modules/kerberos/lib/kerberosgss.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/node_modules/kerberos/lib/sspi.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js rename to node_modules/kerberos/lib/sspi.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/node_modules/kerberos/lib/win32/base64.c similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c rename to node_modules/kerberos/lib/win32/base64.c diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/node_modules/kerberos/lib/win32/base64.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h rename to node_modules/kerberos/lib/win32/base64.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/kerberos/lib/win32/kerberos.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc rename to node_modules/kerberos/lib/win32/kerberos.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/kerberos/lib/win32/kerberos.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h rename to node_modules/kerberos/lib/win32/kerberos.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/kerberos/lib/win32/kerberos_sspi.c similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c rename to node_modules/kerberos/lib/win32/kerberos_sspi.c diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/kerberos/lib/win32/kerberos_sspi.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h rename to node_modules/kerberos/lib/win32/kerberos_sspi.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/node_modules/kerberos/lib/win32/worker.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc rename to node_modules/kerberos/lib/win32/worker.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/node_modules/kerberos/lib/win32/worker.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h rename to node_modules/kerberos/lib/win32/worker.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc rename to node_modules/kerberos/lib/win32/wrappers/security_buffer.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/kerberos/lib/win32/wrappers/security_buffer.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h rename to node_modules/kerberos/lib/win32/wrappers/security_buffer.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/kerberos/lib/win32/wrappers/security_buffer.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js rename to node_modules/kerberos/lib/win32/wrappers/security_buffer.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc rename to node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h rename to node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js rename to node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/kerberos/lib/win32/wrappers/security_context.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc rename to node_modules/kerberos/lib/win32/wrappers/security_context.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/kerberos/lib/win32/wrappers/security_context.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h rename to node_modules/kerberos/lib/win32/wrappers/security_context.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/kerberos/lib/win32/wrappers/security_context.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js rename to node_modules/kerberos/lib/win32/wrappers/security_context.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc rename to node_modules/kerberos/lib/win32/wrappers/security_credentials.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/kerberos/lib/win32/wrappers/security_credentials.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h rename to node_modules/kerberos/lib/win32/wrappers/security_credentials.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/kerberos/lib/win32/wrappers/security_credentials.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js rename to node_modules/kerberos/lib/win32/wrappers/security_credentials.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/node_modules/kerberos/lib/worker.cc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc rename to node_modules/kerberos/lib/worker.cc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/node_modules/kerberos/lib/worker.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h rename to node_modules/kerberos/lib/worker.h diff --git a/node_modules/kerberos/package.json b/node_modules/kerberos/package.json new file mode 100644 index 0000000..24b0410 --- /dev/null +++ b/node_modules/kerberos/package.json @@ -0,0 +1,59 @@ +{ + "_from": "kerberos@0.0.11", + "_id": "kerberos@0.0.11", + "_inBundle": false, + "_integrity": "sha1-yymJHCHCKsGV8xQLl90SIE/qfcI=", + "_location": "/kerberos", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "kerberos@0.0.11", + "name": "kerberos", + "escapedName": "kerberos", + "rawSpec": "0.0.11", + "saveSpec": null, + "fetchSpec": "0.0.11" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.11.tgz", + "_shasum": "cb29891c21c22ac195f3140b97dd12204fea7dc2", + "_spec": "kerberos@0.0.11", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb", + "author": { + "name": "Christian Amor Kvalheim" + }, + "bugs": { + "url": "https://github.com/christkv/kerberos/issues" + }, + "bundleDependencies": false, + "dependencies": { + "nan": "~1.8" + }, + "deprecated": false, + "description": "Kerberos library for Node.js", + "devDependencies": { + "nodeunit": "latest" + }, + "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", + "homepage": "https://github.com/christkv/kerberos#readme", + "keywords": [ + "kerberos", + "security", + "authentication" + ], + "license": "Apache 2.0", + "main": "index.js", + "name": "kerberos", + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/kerberos.git" + }, + "scripts": { + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "nodeunit ./test" + }, + "version": "0.0.11" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/node_modules/kerberos/test/kerberos_tests.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js rename to node_modules/kerberos/test/kerberos_tests.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/kerberos/test/kerberos_win32_test.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js rename to node_modules/kerberos/test/kerberos_win32_test.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js rename to node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/kerberos/test/win32/security_buffer_tests.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js rename to node_modules/kerberos/test/win32/security_buffer_tests.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/kerberos/test/win32/security_credentials_tests.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js rename to node_modules/kerberos/test/win32/security_credentials_tests.js diff --git a/node_modules/mongoose/node_modules/mongodb/.gitmodules b/node_modules/mongodb/.gitmodules similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/.gitmodules rename to node_modules/mongodb/.gitmodules diff --git a/node_modules/mongoose/node_modules/mongodb/.travis.yml b/node_modules/mongodb/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/.travis.yml rename to node_modules/mongodb/.travis.yml diff --git a/node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md b/node_modules/mongodb/CONTRIBUTING.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md rename to node_modules/mongodb/CONTRIBUTING.md diff --git a/node_modules/mongodb/HISTORY b/node_modules/mongodb/HISTORY new file mode 100644 index 0000000..b9e39e6 --- /dev/null +++ b/node_modules/mongodb/HISTORY @@ -0,0 +1,1052 @@ +1.4.38 05-19-2015 +----------------- +- NODE-463 db.close immediately executes its callback. + +1.4.37 2015-05-08 +----------------- +- NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +1.4.36 2015-05-07 +----------------- +- NODE-459 Fixed issue working around breaking changes in crypto lib in 0.10.x vs 0.8.x of node, that broke scram for mongodb 3.0.x. + +1.4.35 2015-03-21 +----------------- +- NODE-389 error out if server does not return a reply or error in connection handler. + +1.4.34 2015-03-09 +----------------- +- NODE-382 Added better SCRAM error handling + +1.4.33 2015-03-03 +----------------- +- Backported NODE-376 Fixes issue - Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) + +1.4.32 2015-02-27 +----------------- +- NODE-369 Unhandled exception while connecting +- Keep numeric error code in query errors (Issue #1259, https://github.com/glasser) + +1.4.31 2015-02-16 +----------------- +- Upgraded kerberos version to 0.0.9 to support node.js 0.12.0 and io.js 1.10.0 +- Emit close on parseError on db for single servers (Issue #1248, https://github.com/vkarpov15) +- listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. + +1.4.30 2015-02-02 +----------------- +- NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. + +1.4.29 2014-01-21 +----------------- +- Updated kerberos to support io.js/node with nan 1.5.1. +- NODE-352 Fixed race-condition for createCollection. + +1.4.28 2014-01-06 +----------------- +- NODE-293 fixed issue for insert on fullResult return due to getRawResponse called incorrectly. + +1.4.27 2014-01-05 +----------------- +- Changed how the ServerCapabilities is populated in the driver to ensure it's always correctly added on High availability checking on ReplSet and Mongos. + +1.4.26 2014-12-22 +----------------- +- Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +1.4.25 2014-12-18 +----------------- +- listCollections filters out index namespaces on < 2.8 correctly +- Use returned ns for getmores when doing command cursors. + +1.4.24 2014-12-18 +----------------- +- Refactored listCollections to return cursor to support 2.8 features correctly. +- Added new listIndexes helper that returns a cursor to support 2.8 features. +- Bumped kerberos to 0.0.7 to correctly compile across win/linus/osx + +1.4.23 2014-12-05 +----------------- +- Fixed minor replicaset reauthentication issues for High availability process. +- Added support for authdb as option for Db.prototype.logout to logout against another db than the current one when authSource has been used. +- Backported 2.0.X test suite to minimize maintenance between 1.4.x branch and 2.0.x. +- Fixed bug on 2.4.x servers when using aggregation cursor and close happens on server connection +- Updated kerberos library to 0.0.6 + +1.4.22 2014-11-20 +----------------- +- NODE-184, Correct message size validation + +1.4.20 2014-11-14 +----------------- +- Removed collectionsInfo method as it's incompatible with 2.8 or higher storage engines due to using namespace collections and a cursor. +- Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +1.4.19 2014-10-09 +----------------- +- Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv). +- NODE-294, slowness in aggregation cursor caused do to batchSize being set to 1 by mistake. +- NODE-293, executing an insert with fullResult true throw TypeError: undefined is not a function. + +1.4.18 2014-10-03 +----------------- +- Cleanup of code removing handleCallback instances +- Throw error on missing callback on createIndex in strict mode (Issue #1214, https://github.com/marneborn) + +1.4.17 2014-09-27 +----------------- +- NODE-286 collection/query.js references undefined MongoError +- NODE-287 "MongoError is not defined" in options command + +1.4.16 2014-09-26 +----------------- +- Fix minor issue due to MongoError usage in options and listCollections + +1.4.15 2014-09-25 +----------------- +- Fix issues with collection.options + +1.4.14 2014-09-24 +----------------- +- Args leak to global namespace fix. + +1.4.13 2014-09-24 +----------------- +- NODE-283 Collection rename now always returns a new Collection object +- Added listCollections helper to Db.prototype +- Scram default authentication mechanism on 2.8 or higher if none is specified + +1.4.12 2014-09-17 +----------------- +- NODE-270 Added better handling of errors on cursor timeouts when calling getMore +- NODE-272 Uncaught Exception at connectionPool.on("message") +- Fixed regression where createIndex sometimes reported index as already existing in non-strict mode due to parallel execution of create commands. + +1.4.11 2014-09-16 +----------------- +- Hardened result handling in command, insert, update, remove for issue where no result is returned. +- NODE-267 undefined variable util used in unordered.js instead of utils. +- Added support for 2.8 listIndexes and listCollections +- Added support for 2.8 SCRAM-SHA-1 mechanism + +1.4.10 2014-09-04 +----------------- +- Fixed BSON and Kerberos compilation issues +- Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +- Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +- Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +- Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +- Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +- Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +- NODE-240 Operations on SSL connection hang on node 0.11.x +- NODE-235 writeResult is not being passed on when error occurs in insert +- NODE-229 Allow count to work with query hints +- NODE-233 collection.save() does not support fullResult +- NODE-244 Should parseError also emit a `disconnected` event? +- NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +- NODE-248 Crash with X509 auth +- NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +- Bumped BSON parser to 0.2.12 + +1.4.8 2014-08-01 +---------------- +- NODE-205 correctly emit authenticate event +- NODE-210 ensure no undefined connection error when checking server state +- NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +- NODE-220 don't throw error if ensureIndex errors out in Gridstore +- Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +- Fixed test running filters +- Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +- False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +- Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +- Fixed parsing issue for w:0 in url parser when in connection string +- Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +- Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +- Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +- Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +- Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +- Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +- Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +- Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +- return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +- Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +- Removed leaking global variable (Issue #1174, https://github.com/dainis) +- MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +- Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +- Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +- Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +- Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +- A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +- Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +- Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +- Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +- Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +- Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +- Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +- Correctly emit joined event when primary change +- Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +- All node exceptions will no longer be caught if on('error') is defined +- Added X509 auth support +- Fix for MongoClient connection timeout issue (NODE-97) +- Pass through error messages from parseError instead of just text (Issue #1125) +- Close db connection on error (Issue #1128, https://github.com/benighted) +- Fixed documentation generation +- Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +- New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +- Insert/Update/Remove using new write commands when available +- Added support for new roles based API's in 2.6 for addUser/removeUser +- Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +- Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +- Support for OP_LOG_REPLAY flag (NODE-94) +- Fixes for SSL HA ping and discovery. +- Uses createIndexes if available for ensureIndex/createIndex +- Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +- Made CommandCursor behave as Readable stream. +- Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +- Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +- GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +- Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +- Refactored commands to all go through command function ensuring consistent command execution. +- Fixed issues where readPreferences where not correctly passed to mongos. +- Catch error == null and make err detection more prominent (NODE-130) +- Allow reads from arbiter for single server connection (NODE-117) +- Handle error coming back with no documents (NODE-130) +- Correctly use close parameter in Gridstore.write() (NODE-125) +- Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +- Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +- Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +- GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +- GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +- Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +- Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +- Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +- Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +- Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +- Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +- Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +- Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +- No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +- Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +- Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +- Ignore return commands that have no registered callback +- Made collection.count not use the db.command function +- Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +- Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +- Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +- Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +- Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +- Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +- BSON size checking now done pre serialization (Issue #1037) +- Added isConnected returns false when no connection Pool exists (Issue #1043) +- Unified command handling to ensure same handling (Issue #1041, #1042) +- Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +- Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +- Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +- Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +- Fixed issue with Kerberos authentication on Windows for re-authentication. +- Fixed Mongos failover behavior to correctly throw out old servers. +- Ensure stored queries/write ops are executed correctly after connection timeout +- Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +- Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +- Fixed bug with callback third parameter on some commands (Issue #1033) +- Fixed possible issue where killcursor command might leave hanging functions +- Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +- Throw error if dbName or collection name contains null character (at command level and at collection level) +- Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +- Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +- Add driver version to export (Issue #1021, https://github.com/aheckmann) +- Add text to readpreference obedient commands (Issue #1019) +- Drivers should check the query failure bit even on getmore response (Issue #1018) +- Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +- Support SASL PLAIN authentication (Issue #1009) +- Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +- Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +- Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +- Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +- Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +- Introduced write and read concerns for GridFS (Issue #996) +- Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +- Fixed issue with pool size on replicaset connections (Issue #1000) +- Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +- Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +- Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +- Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +- Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +- After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +- Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +- Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +- Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +- Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +- Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +- Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +- Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +- Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +- Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +- Applied auth before server instance is set as connected when single server connection +- Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +- Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +- Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +- Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +- Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +- Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +- Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +- Refactored test suite to speed up running of replicaset tests +- Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +- Corrected a slaveOk setting issue (Issue #906, #905) +- Fixed HA issue where ping's would not go to correct server on HA server connection failure. +- Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +- Fixed race condition in Cursor stream (NODE-31) +- Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +- Added support for maxMessageSizeBytes if available (DRIVERS-1) +- Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +- Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +- Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +- Fixed missing MongoErrors on some cursor methods (Issue #882) +- Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +- Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +- Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +- Added limit/skip options to Collection.count (Issue #870) +- Added applySkipLimit option to Cursor.count (Issue #870) +- Enabled ping strategy as default for Replicaset if none specified (Issue #876) +- Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +- Added fixes for handling type 2 binary due to PHP driver (Issue #864) +- Moved callBackStore to Base class to have single unified store (Issue #866) +- Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +- Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +- Only open a new HA socket when previous one dead (Issue #859, #857) +- Minor fixes + +1.2.9 2013-01-15 +---------------- +- Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +- Connection string with no db specified should default to admin db (Issue #848) +- Support port passed as string to Server class (Issue #844) +- Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +- Included toError wrapper code moved to utils.js file (Issue #839, #840) +- Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +- Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +- Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +- Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +- Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +- Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +- Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +- Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +- Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +- Rolled back batches as they hang in certain situations +- Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +- domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +- Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +- Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +- Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +- Fixed ssl regression, added more test coverage (Issue #800) +- Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +- Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +- Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +- Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +- Fix for journal write concern not correctly being passed under some circumstances. +- Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +- Fix for double callback on insert with w:0 specified (Issue #783) +- Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +- Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +- Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +- Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +- Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +- Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +- Force correct setting of read_secondary based on the read preference (Issue #741) +- If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +- noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +- Mongos connection with auth not working (Issue #737) +- Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +- new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + - open/close/db/connect methods implemented +- Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +- Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +- Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +- fix Admin.serverStatus (Issue #723, https://github.com/Contra) +- logging on connection open/close(Issue #721, https://github.com/asiletto) +- more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +- Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +- Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +- Cleanup of non-closing connections (Issue #706) +- More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +- Set keepalive on as default, override if not needed +- Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +- Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +- Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +- Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +- Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +- Proper stopping of strategy on replicaset stop +- Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +- Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +- Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +- Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +- Fix for eval on replicaset Issue #684 +- Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +- Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +- Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +- Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +- Added exhaust option for find for feature completion (not recommended for normal use) +- Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +- Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +- Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +- Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +- Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +- Fix gridfs readstream (Issue #607, https://github.com/tedeh). +- Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +- Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +- Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +- Cleanup map reduce (Issue #614, https://github.com/aheckmann). +- Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +- Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +- Date identification handled correctly in bson js parser when running in vm context. +- Documentation updates +- GridStore filename not set on read (Issue #621) +- Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +- Added support for awaitdata for tailable cursors (Issue #624) +- Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +- Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + - ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +- Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +- Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +- Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +- Fixed auth to work better when multiple connections are involved. +- Default connection pool size increased to 5 connections. +- Fixes for the ReadStream class to work properly with 0.8 of Node.js +- Added explain function support to aggregation helper +- Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +- Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +- Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +- Fixed Always emit db events (Issue #657) +- Close event not correctly resets DB openCalled variable to allow reconnect +- Added open event on connection established for replicaset, mongos and server +- Much faster BSON C++ parser thanks to Lucasfilm Singapore. +- Refactoring of replicaset connection logic to simplify the code. +- Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +- Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +- Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +- Passing back getLastError object as 3rd parameter on findAndModify command. +- Fixed a bunch of performance regressions in objectId and cursor. +- Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +- Fixes to handling of failover on server error +- Only emits error messages if there are error listeners to avoid uncaught events +- Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +- _id=0 is being turned into an ObjectID (Issue #551) +- fix for error in GridStore write method (Issue #559) +- Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +- Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +- Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +- Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +- Connection pools handles closing themselves down and clearing the state +- Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +- Returning update status document at the end of the callback for updates, (Issue #569) +- Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +- Stats not returned from map reduce with inline results (Issue #542) +- Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +- Streaming large files from GridFS causes truncation (Issue #540) +- Make callback type checks agnostic to V8 context boundaries (Issue #545) +- Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +- Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +- BSON parser is externalized in it's own repository, currently using git master +- Fixes for Replicaset connectivity issue (Issue #537) +- Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +- Removed SimpleEmitter and replaced with standard EventEmitter +- GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +- Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +- Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +- Fixed memory leak in C++ bson parser (Issue #526) +- Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +- Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + - Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE b/node_modules/mongodb/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE rename to node_modules/mongodb/LICENSE diff --git a/node_modules/mongoose/node_modules/mongodb/Makefile b/node_modules/mongodb/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/Makefile rename to node_modules/mongodb/Makefile diff --git a/node_modules/mongoose/node_modules/mongodb/Readme.md b/node_modules/mongodb/Readme.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/Readme.md rename to node_modules/mongodb/Readme.md diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongodb/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/index.js rename to node_modules/mongodb/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongodb/lib/mongodb/admin.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js rename to node_modules/mongodb/lib/mongodb/admin.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/aggregation_cursor.js b/node_modules/mongodb/lib/mongodb/aggregation_cursor.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/aggregation_cursor.js rename to node_modules/mongodb/lib/mongodb/aggregation_cursor.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js similarity index 88% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js index 9c08686..424acd1 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js +++ b/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js @@ -35,7 +35,6 @@ var authenticate = function(db, username, password, authdb, options, callback) { // Create a random nonce var nonce = crypto.randomBytes(24).toString('base64'); - // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' var firstBare = f("n=%s,r=%s", username, nonce); // Build command structure @@ -116,16 +115,16 @@ var authenticate = function(db, username, password, authdb, options, callback) { var saltedPassword = hi(passwordDig , new Buffer(salt, 'base64') , iterations); - + // Create the client key var hmac = crypto.createHmac('sha1', saltedPassword); hmac.update(new Buffer("Client Key")); - var clientKey = hmac.digest(); + var clientKey = new Buffer(hmac.digest('base64'), 'base64'); // Create the stored key var hash = crypto.createHash('sha1'); hash.update(clientKey); - var storedKey = hash.digest(); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); // Create the authentication message var authMsg = [firstBare, r.payload.value().toString('base64'), withoutProof].join(','); @@ -133,7 +132,7 @@ var authenticate = function(db, username, password, authdb, options, callback) { // Create client signature var hmac = crypto.createHmac('sha1', storedKey); hmac.update(new Buffer(authMsg)); - var clientSig = hmac.digest(); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); // Create client proof var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); @@ -141,15 +140,16 @@ var authenticate = function(db, username, password, authdb, options, callback) { // Create client final var clientFinal = [withoutProof, clientProof].join(','); + // Generate server key var hmac = crypto.createHmac('sha1', saltedPassword); hmac.update(new Buffer('Server Key')) - var serverKey = hmac.digest(); + var serverKey = new Buffer(hmac.digest('base64'), 'base64'); // Generate server signature var hmac = crypto.createHmac('sha1', serverKey); hmac.update(new Buffer(authMsg)) - var serverSig = hmac.digest(); + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); // // Create continue message @@ -162,19 +162,20 @@ var authenticate = function(db, username, password, authdb, options, callback) { // // Execute sasl continue db.db(authdb).command(cmd, { connection: connection }, function(err, r) { - if(r.done == false) { - var cmd = { - saslContinue: 1 - , conversationId: r.conversationId - , payload: new Buffer(0) - } - - db.db(authdb).command(cmd, { connection: connection }, function(err, r) { - handleEnd(err, r); - }); - } else { - handleEnd(err, r); + if(err) return handleEnd(err, r); + if(r && r.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.conversationId + , payload: new Buffer(0) } + + db.db(authdb).command(cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } }); }); } @@ -230,8 +231,9 @@ var hi = function(data, salt, iterations) { var digest = function(msg) { var hmac = crypto.createHmac('sha1', data); hmac.update(msg); - var result = hmac.digest() - return result; + var result = hmac.digest('base64') + // if(typeof result == 'string') result = new Buffer(result); + return new Buffer(result, 'base64'); } // Create variables diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js rename to node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongodb/lib/mongodb/collection.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js rename to node_modules/mongodb/lib/mongodb/collection.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/aggregation.js b/node_modules/mongodb/lib/mongodb/collection/aggregation.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/aggregation.js rename to node_modules/mongodb/lib/mongodb/collection/aggregation.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/common.js b/node_modules/mongodb/lib/mongodb/collection/batch/common.js similarity index 99% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/common.js rename to node_modules/mongodb/lib/mongodb/collection/batch/common.js index c31c364..3a6cb4b 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/common.js +++ b/node_modules/mongodb/lib/mongodb/collection/batch/common.js @@ -34,6 +34,7 @@ var Batch = function(batchType, originalZeroIndex) { this.batchType = batchType; this.operations = []; this.size = 0; + this.sizeBytes = 0; } /** diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js b/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js rename to node_modules/mongodb/lib/mongodb/collection/batch/ordered.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js b/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js similarity index 94% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js rename to node_modules/mongodb/lib/mongodb/collection/batch/unordered.js index 0024708..f62ccdb 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js +++ b/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js @@ -34,11 +34,8 @@ var UnorderedBulkOperation = function(collection, options) { var executed = false; // Current item - // var currentBatch = null; var currentOp = null; var currentIndex = 0; - var currentBatchSize = 0; - var currentBatchSizeBytes = 0; var batches = []; // The current Batches for the different operations @@ -207,35 +204,15 @@ var UnorderedBulkOperation = function(collection, options) { // Create a new batch object if we don't have a current one if(currentBatch == null) currentBatch = new Batch(docType, currentIndex); - // Check if we need to switch batch type - if(currentBatch.batchType != docType) { - // Save current batch - batches.push(currentBatch); - // Create a new batch - currentBatch = new Batch(docType, currentIndex); - - // Reset the current size trackers - currentBatchSize = 0; - currentBatchSizeBytes = 0; - } - // Check if we need to create a new batch - if(((currentBatchSize + 1) >= maxWriteBatchSize) - || ((currentBatchSizeBytes + currentBatchSizeBytes) >= maxBatchSizeBytes) + if(((currentBatch.size + 1) >= maxWriteBatchSize) + || ((currentBatch.sizeBytes + bsonSize) >= maxBatchSizeBytes) || (currentBatch.batchType != docType)) { // Save the batch to the execution stack batches.push(currentBatch); // Create a new batch currentBatch = new Batch(docType, currentIndex); - - // Reset the current size trackers - currentBatchSize = 0; - currentBatchSizeBytes = 0; - } else { - // Update current batch size - currentBatchSize = currentBatchSize + 1; - currentBatchSizeBytes = currentBatchSizeBytes + bsonSize; } // We have an array of documents @@ -257,8 +234,8 @@ var UnorderedBulkOperation = function(collection, options) { } // Update current batch size - currentBatchSize = currentBatchSize + 1; - currentBatchSizeBytes = currentBatchSizeBytes + bsonSize; + currentBatch.size = currentBatch.size + 1; + currentBatch.sizeBytes = currentBatch.sizeBytes + bsonSize; // Return self return _self; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/commands.js b/node_modules/mongodb/lib/mongodb/collection/commands.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/commands.js rename to node_modules/mongodb/lib/mongodb/collection/commands.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js b/node_modules/mongodb/lib/mongodb/collection/core.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js rename to node_modules/mongodb/lib/mongodb/collection/core.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/geo.js b/node_modules/mongodb/lib/mongodb/collection/geo.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/geo.js rename to node_modules/mongodb/lib/mongodb/collection/geo.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/index.js b/node_modules/mongodb/lib/mongodb/collection/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/index.js rename to node_modules/mongodb/lib/mongodb/collection/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/query.js b/node_modules/mongodb/lib/mongodb/collection/query.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/query.js rename to node_modules/mongodb/lib/mongodb/collection/query.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/shared.js b/node_modules/mongodb/lib/mongodb/collection/shared.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/shared.js rename to node_modules/mongodb/lib/mongodb/collection/shared.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/command_cursor.js b/node_modules/mongodb/lib/mongodb/command_cursor.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/command_cursor.js rename to node_modules/mongodb/lib/mongodb/command_cursor.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongodb/lib/mongodb/commands/base_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js rename to node_modules/mongodb/lib/mongodb/commands/base_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongodb/lib/mongodb/commands/db_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js rename to node_modules/mongodb/lib/mongodb/commands/db_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongodb/lib/mongodb/commands/delete_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js rename to node_modules/mongodb/lib/mongodb/commands/delete_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongodb/lib/mongodb/commands/get_more_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js rename to node_modules/mongodb/lib/mongodb/commands/get_more_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongodb/lib/mongodb/commands/insert_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js rename to node_modules/mongodb/lib/mongodb/commands/insert_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js rename to node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongodb/lib/mongodb/commands/query_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js rename to node_modules/mongodb/lib/mongodb/commands/query_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongodb/lib/mongodb/commands/update_command.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js rename to node_modules/mongodb/lib/mongodb/commands/update_command.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongodb/lib/mongodb/connection/base.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js rename to node_modules/mongodb/lib/mongodb/connection/base.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongodb/lib/mongodb/connection/connection.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js rename to node_modules/mongodb/lib/mongodb/connection/connection.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongodb/lib/mongodb/connection/connection_pool.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js rename to node_modules/mongodb/lib/mongodb/connection/connection_pool.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongodb/lib/mongodb/connection/connection_utils.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js rename to node_modules/mongodb/lib/mongodb/connection/connection_utils.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongodb/lib/mongodb/connection/mongos.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js rename to node_modules/mongodb/lib/mongodb/connection/mongos.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongodb/lib/mongodb/connection/read_preference.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js rename to node_modules/mongodb/lib/mongodb/connection/read_preference.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/options.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js rename to node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongodb/lib/mongodb/connection/server.js similarity index 99% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js rename to node_modules/mongodb/lib/mongodb/connection/server.js index 2c65374..e991deb 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js +++ b/node_modules/mongodb/lib/mongodb/connection/server.js @@ -360,6 +360,7 @@ Server.prototype.connect = function(dbInstance, options, callback) { if(err != null && internalCallback == null) return; // Internal callback if(err != null) return internalCallback(err, null, _server); + if(reply == null || reply.documents == null) return internalCallback(utils.toError("server failed to respond", 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); diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js rename to node_modules/mongodb/lib/mongodb/connection/server_capabilities.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongodb/lib/mongodb/connection/url_parser.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js rename to node_modules/mongodb/lib/mongodb/connection/url_parser.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongodb/lib/mongodb/cursor.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js rename to node_modules/mongodb/lib/mongodb/cursor.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongodb/lib/mongodb/cursorstream.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js rename to node_modules/mongodb/lib/mongodb/cursorstream.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongodb/lib/mongodb/db.js similarity index 99% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js rename to node_modules/mongodb/lib/mongodb/db.js index c7c4bf3..f7f1143 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js +++ b/node_modules/mongodb/lib/mongodb/db.js @@ -361,7 +361,9 @@ Db.prototype.close = function(forceClose, callback) { // You can reuse the db as everything is shut down self.openCalled = false; // If we have a callback call it - if(callback) callback(err, result); + if(callback) process.nextTick(function() { + callback(err, result); + }); }); }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongodb/lib/mongodb/gridfs/chunk.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js rename to node_modules/mongodb/lib/mongodb/gridfs/chunk.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongodb/lib/mongodb/gridfs/grid.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js rename to node_modules/mongodb/lib/mongodb/gridfs/grid.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js similarity index 98% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js rename to node_modules/mongodb/lib/mongodb/gridfs/gridstore.js index c6b9894..8405d3f 100644 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js +++ b/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js @@ -861,28 +861,22 @@ GridStore.prototype.seek = function(position, seekLocation, callback) { // Get the chunk var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - if(newChunkNumber != self.currentChunk.chunkNumber) { - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; - if(self.mode[0] == 'w') { - self.currentChunk.save({}, function(err) { - if(err) return callback(err); - seekChunk(); - }); - } else { + if(self.mode[0] == 'w') { + self.currentChunk.save({}, function(err) { + if(err) return callback(err); seekChunk(); - } + }); } else { - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(null, self); + seekChunk(); } }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongodb/lib/mongodb/gridfs/readstream.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js rename to node_modules/mongodb/lib/mongodb/gridfs/readstream.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongodb/lib/mongodb/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js rename to node_modules/mongodb/lib/mongodb/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongodb/lib/mongodb/mongo_client.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js rename to node_modules/mongodb/lib/mongodb/mongo_client.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js rename to node_modules/mongodb/lib/mongodb/responses/mongo_reply.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/scope.js b/node_modules/mongodb/lib/mongodb/scope.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/scope.js rename to node_modules/mongodb/lib/mongodb/scope.js diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongodb/lib/mongodb/utils.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js rename to node_modules/mongodb/lib/mongodb/utils.js diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongodb/package.json similarity index 78% rename from node_modules/mongoose/node_modules/mongodb/package.json rename to node_modules/mongodb/package.json index dc9a486..56fb31e 100644 --- a/node_modules/mongoose/node_modules/mongodb/package.json +++ b/node_modules/mongodb/package.json @@ -1,17 +1,38 @@ { - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" + "_from": "mongodb@1.4.38", + "_id": "mongodb@1.4.38", + "_inBundle": false, + "_integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "_location": "/mongodb", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongodb@1.4.38", + "name": "mongodb", + "escapedName": "mongodb", + "rawSpec": "1.4.38", + "saveSpec": null, + "fetchSpec": "1.4.38" + }, + "_requiredBy": [ + "/mongoose" ], - "version": "1.4.32", + "_resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", + "_shasum": "8cffd618100af3a4648a995498bfcfcb4ed8abd2", + "_spec": "mongodb@1.4.38", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", "author": { "name": "Christian Amor Kvalheim", "email": "christkv@gmail.com" }, + "bugs": { + "url": "http://github.com/mongodb/node-mongodb-native/issues" + }, + "bundleDependencies": false, + "config": { + "native": false + }, "contributors": [ { "name": "Aaron Heckmann" @@ -176,77 +197,59 @@ "name": "Samantha Ritter" } ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, "dependencies": { "bson": "~0.2", - "kerberos": "0.0.9", + "kerberos": "0.0.11", "readable-stream": "latest" }, + "deprecated": "Please upgrade to 2.2.19 or higher", + "description": "A node.js driver for MongoDB", "devDependencies": { "dox": "0.4.4", - "uglify-js": "1.2.5", "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.3", - "markdown": "0.3.1", "gleak": "0.5.0", - "step": "0.0.5", - "async": "0.1.22", "integra": "0.1.8", + "markdown": "0.3.1", + "mongodb-tools": "~1.0", + "mongodb-version-manager": "0.7.0", + "nodeunit": "0.7.3", "optimist": "latest", + "request": "2.12.0", "rimraf": "2.2.6", "semver": "4.1.0", - "mongodb-version-manager": "0.5.0", - "mongodb-tools": "~1.0" - }, - "optionalDependencies": { - "kerberos": "0.0.9", - "readable-stream": "latest" - }, - "config": { - "native": false + "uglify-js": "1.2.5" }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", "directories": { "lib": "./lib/mongodb" }, "engines": { "node": ">=0.6.19" }, - "scripts": { - "test": "node test/runner.js -t functional" - }, + "homepage": "http://mongodb.github.com/node-mongodb-native/", + "keywords": [ + "mongodb", + "mongo", + "driver", + "db" + ], "licenses": [ { "type": "Apache License, Version 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0" } ], - "gitHead": "bc37b5d83fdaf6a0836c6658697458d7a7ca65f5", - "_id": "mongodb@1.4.32", - "_shasum": "23043d743e507e73e37c3eef03916af5ba0333b8", - "_from": "mongodb@1.4.32", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" + "main": "./lib/mongodb/index", + "name": "mongodb", + "optionalDependencies": { + "kerberos": "0.0.11", + "readable-stream": "latest" }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "23043d743e507e73e37c3eef03916af5ba0333b8", - "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.32.tgz" + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "scripts": { + "test": "node test/runner.js -t functional" }, - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-1.4.32.tgz" + "version": "1.4.38" } diff --git a/node_modules/mongodb/repo_node_418.js b/node_modules/mongodb/repo_node_418.js new file mode 100644 index 0000000..6ef5f9f --- /dev/null +++ b/node_modules/mongodb/repo_node_418.js @@ -0,0 +1,33 @@ +var mongodb = require('./'); +var mongo_hosts = 'localhost:31000,localhost:31001,localhost:31002'; +var mongo_user = 'bla'; +var mongo_pass = 'bla bla'; +var mongo_db = 'admin'; +var mongoUrl = 'mongodb://' + mongo_user + ':' + mongo_pass + '@' + mongo_hosts + '/' + mongo_db + '?autoReconnect=true&w=0'; +var mongoUrl = 'mongodb://' + mongo_hosts + '/' + mongo_db + '?autoReconnect=true&w=0'; + +var func = function() { + console.log('Connecting'); + + // Connect + mongodb.connect(mongoUrl, function(err, client) { + if (err) { + console.log("Error connecting to mongo: %s, err: %s", mongoUrl, err); + client && client.close(); + } else { + console.log("connected to mongo: " + mongoUrl); + var db = client.db('mbrewer-test_playpen_meteor_com'); + + db.removeUser('fakeUser', {}, function (err) { + console.log("Removed user ... (error " + err + ")"); + client.close(); + }); + } + + console.log('Scheduling our next call'); + setTimeout(func, 1); + }); +} + +console.log('Starting'); +func(); \ No newline at end of file diff --git a/node_modules/mongodb/wercker.yml b/node_modules/mongodb/wercker.yml new file mode 100644 index 0000000..db008ae --- /dev/null +++ b/node_modules/mongodb/wercker.yml @@ -0,0 +1,17 @@ +box: wercker/nodejs +# Build definition +build: + # The steps that will be executed on build + steps: + # A step that executes `npm install` command + - npm-install + # A step that executes `npm test` command + - npm-test + + # A custom script step, name value is used in the UI + # and the code value contains the command that get executed + - script: + name: echo nodejs information + code: | + echo "node version $(node -v) running" + echo "npm version $(npm -v) running" diff --git a/node_modules/mongoose/.travis.yml b/node_modules/mongoose/.travis.yml index dcaf0f1..10aeedb 100644 --- a/node_modules/mongoose/.travis.yml +++ b/node_modules/mongoose/.travis.yml @@ -1,6 +1,6 @@ language: node_js node_js: - - 0.8 - - 0.10 + - "0.8" + - "0.10" services: - mongodb diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md index 8a6ecf2..a3ad4eb 100644 --- a/node_modules/mongoose/History.md +++ b/node_modules/mongoose/History.md @@ -1,3 +1,47 @@ +3.8.40 / 2016-04-24 +=================== + * upgraded; mquery -> 1.10.0 #3989 + +3.8.39 / 2016-01-15 +=================== + * fixed; casting a number to a buffer #3764 + * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold) + +3.8.38 / 2016-01-07 +=================== + * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup) + +3.8.37 / 2015-11-16 +=================== + * fixed; use retainKeyOrder for cloning update op #3572 + +3.8.36 / 2015-10-18 +=================== + * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer) + +3.8.35 / 2015-08-14 +=================== + * fixed; handling for minimize on nested objects #2930 + * fixed; don't crash when schema.path.options undefined #1824 + +3.8.34 / 2015-07-20 +=================== + * fixed; allow using $rename #3171 + * fixed; no longer modifies update arguments #3008 + +3.8.33 / 2015-07-10 +=================== + * upgraded; node driver -> 1.4.38 + * fixed; dont crash when `match` validator undefined + +3.8.31 / 2015-06-20 +=================== + * fixed; properly handle text search with discriminators and $meta #2166 + +3.8.30 / 2015-06-05 +=================== + * fixed; enable users to set all options with tailable() #2883 + 3.8.29 / 2015-05-27 =================== * fixed; Handle JSON.stringify properly for nested docs #2990 diff --git a/node_modules/mongoose/bin/mongoose.min.js b/node_modules/mongoose/bin/mongoose.min.js index 4cd0e28..9c0478e 100644 --- a/node_modules/mongoose/bin/mongoose.min.js +++ b/node_modules/mongoose/bin/mongoose.min.js @@ -1,6 +1,10 @@ -!function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){var r=e[s][1][t];return i(r?r:t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;sr;++r)Object.defineProperty(t,i[r],{enumerable:!1,writable:!0,configurable:!0,value:void 0});t.toObject=function(){return this.get(s)},t.toJSON=t.toObject,a(e,t,s),this.$__.getters[s]=t}return this.$__.getters[s]},set:function(t){return t instanceof o&&(t=t.toObject()),(this.$__.scope||this).set(s,t)}}):Object.defineProperty(r,t,{enumerable:!0,configurable:!0,get:function(){return this.get.call(this.$__.scope||this,s)},set:function(t){return this.set.call(this.$__.scope||this,s,t)}})}function c(t){for(var e,r,n,i=Object.keys(t),o=i.length;o--;)r=i[o],n=t[r],b.isObject(n)&&(t[r]=c(n)),void 0!==t[r]?e=!0:delete t[r];return e?t:void 0}function h(t,e,r,n){for(var i,o=t.schema,s=Object.keys(o[r]),a=s.length;a--;){i=s[a];for(var u,f=i.split("."),c=f.length,h=c-1,p=e,l=0;c>l;++l)u=f[l],l===h?p[u]=w(t.get(i),n):p=p[u]||(p[u]={})}return e}var p,l,d,y=t("events").EventEmitter,g=(y.prototype.setMaxListeners,t("./error")),_=t("./schema/mixed"),m=t("./schema"),v=(t("./types/objectid"),t("./schematype").ValidatorError),b=t("./utils"),w=b.clone,O=b.isMongooseObject,B=t("util").inspect,A=g.ValidationError,E=t("./internal"),S=b.deepEqual,N=t("hooks-fixed"),T=t("./promise");b.each(["on","once","emit","listeners","removeListener","setMaxListeners","removeAllListeners","addListener"],function(t){o.prototype[t]=function(){return this.$__.emitter[t].apply(this.$__.emitter,arguments)}}),o.prototype.constructor=o,o.prototype.schema,o.prototype.isNew,o.prototype.id,o.prototype.errors,o.prototype.$__buildDoc=function(t,e,r){var n,i,o,s={},a=this;if(e&&"Object"===b.getFunctionName(e.constructor))for(i=Object.keys(e),o=i.length;o--;)if("_id"!==i[o]){n=0===e[i[o]];break}for(var u=Object.keys(this.schema.paths),f=u.length,c=0;f>c;++c){var h=u[c];if("_id"==h){if(r)continue;if(t&&"_id"in t)continue}for(var p=this.schema.paths[h],l=h.split("."),d=l.length,y=d-1,g="",_=s,m=0,v=!1;d>m;++m){var w,O=l[m];if(g+=O,n){if(g in e)break}else e&&g in e&&(v=!0);if(m===y)if(e)if(n){if(h in e)continue;w=p.getDefault(a,!0),"undefined"!=typeof w&&(_[O]=w,a.$__.activePaths.default(h))}else v&&(w=p.getDefault(a,!0),"undefined"!=typeof w&&(_[O]=w,a.$__.activePaths.default(h)));else w=p.getDefault(a,!0),"undefined"!=typeof w&&(_[O]=w,a.$__.activePaths.default(h));else _=_[O]||(_[O]={}),g+="."}}return s},o.prototype.init=function(t,e,r){if("function"==typeof e&&(r=e,e=null),this.isNew=!1,null!=t._id&&e&&e.populated&&e.populated.length)for(var n=String(t._id),i=0;io;++o)e=this.getValue(n[o]),r[n[o]]=O(e)?e.toObject({depopulate:!0}):null==e||!e.valueOf||e.constructor&&"Date"===b.getFunctionName(e.constructor)?e:e.valueOf()};for(var $ in N)o.prototype[$]=o[$]=N[$];o.prototype.update=function(){var t=b.args(arguments);return t.unshift({_id:this._id}),this.constructor.update.apply(this.constructor,t)},o.prototype.set=function(t,e,r,n){r&&"Object"==b.getFunctionName(r.constructor)&&(n=r,r=void 0);var i,s=n&&n.merge,a=r&&!0!==r,u=!0===r,f=n&&"strict"in n?n.strict:this.$__.strictMode;if(a&&(i=this.$__.adhocPaths||(this.$__.adhocPaths={}),i[t]=m.interpretAsType(t,r)),"string"!=typeof t){if(null!==t&&void 0!==t){var c=e?e+".":"";t instanceof o&&(t=t._doc);for(var h,p,l=Object.keys(t),d=l.length;d--;){p=l[d];var y=c+p;if(h=this.schema.pathType(y),null==t[p]||!b.isObject(t[p])||t[p].constructor&&"Object"!=b.getFunctionName(t[p].constructor)||"virtual"==h||this.$__path(y)instanceof _||this.schema.paths[y]&&this.schema.paths[y].options.ref)if(f){if("real"===h||"virtual"===h)this.set(c+p,t[p],u);else if("throw"==f)throw new Error("Field `"+p+"` is not in schema.")}else void 0!==t[p]&&this.set(c+p,t[p],u);else this.set(t[p],c+p,u)}return this}var v=t;t=e,e=v}var w=this.schema.pathType(t);if("nested"==w&&e)return!b.isObject(e)||e.constructor&&"Object"!=b.getFunctionName(e.constructor)?(this.invalidate(t,new g.CastError("Object",e,t)),this):(s||this.setValue(t,null),this.set(e,t,u),this);var O,B=t.split(".");if("adhocOrUndefined"==w&&f){for(var A,d=0;dc;c++){var p=c+1,y=p===h;y?f[i[c]]=s:f=f[i[c]]&&"Object"===b.getFunctionName(f[i[c]].constructor)?f[i[c]]:f[i[c]]&&f[i[c]]instanceof d?f[i[c]]:f[i[c]]&&Array.isArray(f[i[c]])?f[i[c]]:f[i[c]]={}}},o.prototype.getValue=function(t){return b.getValue(t,this._doc)},o.prototype.setValue=function(t,e){return b.setValue(t,e,this._doc),this},o.prototype.get=function(t,e){var r;e&&(r=m.interpretAsType(t,e));for(var n=this.$__path(t)||this.schema.virtualpath(t),i=t.split("."),o=this._doc,s=0,a=i.length;a>s;s++)o=void 0===o||null===o?void 0:o[i[s]];return r&&(o=r.cast(o)),n&&(o=n.applyGetters(o,this)),o},o.prototype.$__path=function(t){var e=this.$__.adhocPaths,r=e&&e[t];return r?r:this.schema.path(t)},o.prototype.markModified=function(t){this.$__.activePaths.modify(t)},o.prototype.modifiedPaths=function(){var t=Object.keys(this.$__.activePaths.states.modify);return t.reduce(function(t,e){var r=e.split(".");return t.concat(r.reduce(function(t,e,n){return t.concat(r.slice(0,n).concat(e).join("."))},[]))},[])},o.prototype.isModified=function(t){return t?!!~this.modifiedPaths().indexOf(t):this.$__.activePaths.some("modify")},o.prototype.isDirectModified=function(t){return t in this.$__.activePaths.states.modify},o.prototype.isInit=function(t){return t in this.$__.activePaths.states.init},o.prototype.isSelected=function(t){if(this.$__.selected){if("_id"===t)return 0!==this.$__.selected._id;var e,r=Object.keys(this.$__.selected),n=r.length,i=!1;if(1===n&&"_id"===r[0])return 0===this.$__.selected._id;for(;n--;)if(e=r[n],"_id"!=e){i=!!this.$__.selected[e];break}if(t in this.$__.selected)return i;n=r.length;for(var o=t+".";n--;)if(e=r[n],"_id"!=e){if(0===e.indexOf(o))return i;if(0===o.indexOf(e+"."))return i}return!i}return!0},o.prototype.validate=function(t){function e(t){u[t]||(u[t]=!0,f++,n.nextTick(function(){var e=o.schema.path(t);if(!e)return--f||r();if(!o.$isValid(t))return void(--f||r());var n=o.getValue(t);e.doValidate(n,function(e){e&&o.invalidate(t,e,void 0,!0),--f||r()},o)}))}function r(){var t=o.$__.validationError;if(o.$__.validationError=void 0,o.emit("validate",o),t){for(var e in t.errors)!o.__parent&&t.errors[e]instanceof g.CastError&&o.invalidate(e,t.errors[e]);s.reject(t)}else s.fulfill()}var o=this,s=new T(t),a=Object.keys(this.$__.activePaths.states.require).filter(function(t){return o.isSelected(t)||o.isModified(t)?!0:!1});if(a=a.concat(Object.keys(this.$__.activePaths.states.init)),a=a.concat(Object.keys(this.$__.activePaths.states.modify)),a=a.concat(Object.keys(this.$__.activePaths.states.default)),0===a.length)return n.nextTick(function(){r()}),s;for(var u={},f=0,c=0;cd;++d)a.push(h+"."+d)}return a.forEach(e),s},o.prototype.validateSync=function(){var t=this,e=Object.keys(this.$__.activePaths.states.require).filter(function(e){return t.isSelected(e)||t.isModified(e)?!0:!1});e=e.concat(Object.keys(this.$__.activePaths.states.init)),e=e.concat(Object.keys(this.$__.activePaths.states.modify)),e=e.concat(Object.keys(this.$__.activePaths.states.default));var r={};e.forEach(function(e){if(!r[e]){r[e]=!0;var n=t.schema.path(e);if(n&&t.$isValid(e)){var i=t.getValue(e),o=n.doValidateSync(i,t);o&&t.invalidate(e,o,void 0,!0)}}});var n=t.$__.validationError;if(t.$__.validationError=void 0,t.emit("validate",t),n)for(var i in n.errors)n.errors[i]instanceof g.CastError&&t.invalidate(i,n.errors[i]);return n},o.prototype.invalidate=function(t,e,r){this.$__.validationError||(this.$__.validationError=new A(this)),this.$__.validationError.errors[t]||(e&&"string"!=typeof e||(e=new v({path:t,message:e,type:"user defined",value:r})),this.$__.validationError!=e&&(this.$__.validationError.errors[t]=e))},o.prototype.$markValid=function(t){this.$__.validationError&&this.$__.validationError.errors[t]&&(delete this.$__.validationError.errors[t],0===Object.keys(this.$__.validationError.errors).length&&(this.$__.validationError=null))},o.prototype.$isValid=function(t){return!this.$__.validationError||!this.$__.validationError.errors[t]},o.prototype.$__reset=function(){var e=this;p||(p=t("./types/documentarray")),this.$__.activePaths.map("init","modify",function(t){return e.getValue(t)}).filter(function(t){return t&&t instanceof Array&&t.isMongooseDocumentArray&&t.length}).forEach(function(t){for(var e=t.length;e--;){var r=t[e];r&&r.$__reset()}}),this.$__dirty().forEach(function(t){var e=t.value;e&&e._atomics&&(e._atomics={})}),this.$__.activePaths.clear("modify"),this.$__.validationError=void 0,this.errors=void 0;var e=this;return this.schema.requiredPaths().forEach(function(t){e.$__.activePaths.require(t)}),this},o.prototype.$__dirty=function(){var t=this,e=this.$__.activePaths.map("modify",function(e){return{path:e,value:t.getValue(e),schema:t.$__path(e)}});e=e.concat(this.$__.activePaths.map("default",function(e){return"_id"!==e&&t.getValue(e)?{path:e,value:t.getValue(e),schema:t.$__path(e)}:void 0})),e.sort(function(t,e){return t.pathe.path?1:0});var r,n,i=[];return e.forEach(function(t){t&&(0!==t.path.indexOf(r)?(r=t.path+".",i.push(t),n=t):n.value&&n.value._atomics&&n.value.hasAtomics()&&(n.value._atomics={},n.value._atomics.$set=n.value))}),n=r=null,i},o.prototype.$__setSchema=function(t){a(t.tree,this),this.schema=t},o.prototype.$__getArrayPathsToValidate=function(){return p||(p=t("./types/documentarray")),this.$__.activePaths.map("init","modify",function(t){return this.getValue(t)}.bind(this)).filter(function(t){return t&&t instanceof Array&&t.isMongooseDocumentArray&&t.length}).reduce(function(t,e){return t.concat(e)},[]).filter(function(t){return t})},o.prototype.$__getAllSubdocs=function(){function e(t,r){var n=this[r];return n instanceof d&&t.push(n),n&&n.isMongooseDocumentArray&&n.forEach(function(r){r&&r._doc&&(r instanceof d&&t.push(r),t=Object.keys(r._doc).reduce(e.bind(r._doc),t))}),t}p||(p=t("./types/documentarray")),d=d||t("./types/embedded");var r=Object.keys(this._doc).reduce(e.bind(this),[]);return r},o.prototype.$__registerHooksFromSchema=function(){d=d||t("./types/embedded");var e=this,r=e.schema&&e.schema.callQueue;if(!r.length)return e;var n=r.reduce(function(t,r){if("pre"!==r[0]&&"post"!==r[0]&&"on"!==r[0])return e[r[0]].apply(e,r[1]),t;var n=[].slice.call(r[1]),i="on"===r[0]?"post":n[0];return i in t||(t[i]=[]),t[i].push(n),t},{post:[]});return n.post.forEach(function(t){e.on.apply(e,t)}),delete n.post,Object.keys(n).forEach(function(t){if(~"set ".indexOf(t))return void n[t].forEach(function(t){e.pre.apply(e,t)});var r="$__original_"+t;e[t]&&(e[r]=e[t],e[t]=function(){var t=[].slice.call(arguments),n=t.pop(),i=new T;return i.end(),"function"==typeof n&&i.onResolve(n),this instanceof d||i.hasRejectListeners()||i.onReject(e.$__handleReject.bind(e)),t.push(function(){return i.resolve.apply(i,arguments)}),e[r].apply(e,t),i},n[t].forEach(function(t){t[0]=r,e.pre.apply(e,t)}))}),e},o.prototype.$__handleReject=function(t){this.listeners("error").length?this.emit("error",t):this.constructor.listeners&&this.constructor.listeners("error").length?this.constructor.emit("error",t):this.listeners&&this.listeners("error").length&&this.emit("error",t)},o.prototype.$toObject=function(t,e){var r={transform:!0,json:e};if(t&&t.depopulate&&!t._skipDepopulateTopLevel&&this.$__.wasPopulated)return w(this._id,t);t&&t._skipDepopulateTopLevel&&(t._skipDepopulateTopLevel=!1);var n=t;(!t||"Object"!=b.getFunctionName(t.constructor)||t&&t._useSchemaOptions)&&(t=e?this.schema.options.toJSON?w(this.schema.options.toJSON):{}:this.schema.options.toObject?w(this.schema.options.toObject):{});for(var i in r)void 0===t[i]&&(t[i]=r[i]);"minimize"in t||(t.minimize=this.schema.options.minimize),n||(t._useSchemaOptions=!0);var o=t.transform,s=w(this._doc,t);(t.virtuals||t.getters&&!1!==t.virtuals)&&h(this,s,"virtuals",t),t.getters&&(h(this,s,"paths",t),t.minimize&&(s=c(s)||{})),t.versionKey===!1&&this.schema.options.versionKey&&delete s[this.schema.options.versionKey];var a=t.transform;if(!0===a||this.schema.options.toObject&&a){var u=t.json?this.schema.options.toJSON:this.schema.options.toObject;u&&(a="function"==typeof t.transform?t.transform:u.transform)}else t.transform=o;if("function"==typeof a){var f=a(this,s,t);"undefined"!=typeof f&&(s=f)}return s},o.prototype.toObject=function(t){return this.$toObject(t)},o.prototype.toJSON=function(t){return this.$toObject(t,!0)},o.prototype.inspect=function(t){var e=t&&"Object"==b.getFunctionName(t.constructor)?t:{};return e.minimize=!1,B(this.toObject(e))},o.prototype.toString=o.prototype.inspect,o.prototype.equals=function(t){var e=this.get("_id"),r=t.get("_id");return e||r?e&&e.equals?e.equals(r):e===r:S(this,t)},o.prototype.populate=function(){if(0===arguments.length)return this;var t,e=this.$__.populate||(this.$__.populate={}),r=b.args(arguments);if("function"==typeof r[r.length-1]&&(t=r.pop()),r.length)for(var n=b.populate.apply(null,r),i=0;in;++n)t(e[n],this.paths[e[n]]);return this},i.prototype.requiredPaths=function(){if(this._requiredpaths)return this._requiredpaths;for(var t=Object.keys(this.paths),e=t.length,r=[];e--;){var n=t[e];this.paths[n].isRequired&&r.push(n)}return this._requiredpaths=r},i.prototype.indexedPaths=function(){return this._indexedpaths?this._indexedpaths:this._indexedpaths=this.indexes()},i.prototype.pathType=function(t){return t in this.paths?"real":t in this.virtuals?"virtual":t in this.nested?"nested":t in this.subpaths?"real":/\.\d+\.|\.\d+$/.test(t)&&s(this,t)?"real":"adhocOrUndefined"},i.prototype.queue=function(t,e){return this.callQueue.push([t,e]),this},i.prototype.pre=function(){var t=arguments[0];return p[t]?(this.s.hooks.pre.apply(this.s.hooks,arguments),this):this.queue("pre",arguments)},i.prototype.post=function(t,e){return p[t]?(this.s.hooks.post.apply(this.s.hooks,arguments),this):e.length<2?this.queue("on",[arguments[0],function(t){return e.call(t,t)}]):this.queue("post",[arguments[0],function(t){e.call(this,this,t)}])},i.prototype.plugin=function(t,e){return t(this,e),this},i.prototype.method=function(t,e){if("string"!=typeof t)for(var r in t)this.methods[r]=t[r];else this.methods[t]=e;return this},i.prototype.static=function(t,e){if("string"!=typeof t)for(var r in t)this.statics[r]=t[r];else this.statics[t]=e;return this},i.prototype.index=function(t,e){return e||(e={}),e.expires&&c.expires(e),this._indexes.push([t,e]),this},i.prototype.set=function(t,e,r){if(1===arguments.length)return this.options[t];switch(t){case"read":this.options[t]=c.readPref(e,r);break;case"safe":this.options[t]=!1===e?{w:0}:e;break;default:this.options[t]=e}return this},i.prototype.get=function(t){return this.options[t]};var d="2d 2dsphere hashed text".split(" ");Object.defineProperty(i,"indexTypes",{get:function(){return d},set:function(){throw new Error("Cannot overwrite Schema.indexTypes")}}),i.prototype.indexes=function(){"use strict";function t(t,r){var n,i,o,s,a,u,f=t._indexes,c=f.length,h=0;for(h=0;c>h;++h){for(n=f[h][0],s=Object.keys(n),o=s.length,i={},u=0;o>u;++u)a=s[u],i[r+a]=n[a];e.push([i,f[h][1]])}}var e=[],r={},n=function(o,s){if(!r[s]){r[s]=!0,s=s||"";for(var u,f,h,p,l,d,y,g=Object.keys(o.paths),_=0;_s;++s){var e=i[s],r=t[e];0===e.indexOf("$")&&r&&(t[e]=this.castForQuery(e,r),n=!0)}return n?t:_(this.casterConstructor.schema,t)}function c(t){var e=t.$geometry;if(e)return s(t,this),t}var h=t("../schematype"),p=h.CastError,l=(t("./number"),{Boolean:t("./boolean"),Date:t("./date"),Number:t("./number"),String:t("./string"),ObjectId:t("./objectid"),Buffer:t("./buffer")}),d=t("../types").Array,y=t("../types").Embedded,g=t("./mixed"),_=t("../cast"),m=t("../utils"),v=m.isMongooseObject;r.schemaName="Array",r.prototype=Object.create(h.prototype),r.prototype.constructor=r,r.prototype.checkRequired=function(t){return!(!t||!t.length)},r.prototype.applyGetters=function(t,e){return this.caster.options&&this.caster.options.ref?t:h.prototype.applyGetters.call(this,t,e)},r.prototype.cast=function(t,e,r){if(Array.isArray(t)){if(!t.length&&e)for(var n=e.schema.indexedPaths(),i=0,o=n.length;o>i;++i){var s=n[i][0][this.path];if("2dsphere"===s||"2d"===s)return}if(t&&t.isMongooseArray||(t=new d(t,this.path,e)),this.caster)try{for(var i=0,o=t.length;o>i;i++)t[i]=this.caster.cast(t[i],e,r)}catch(e){throw new p(e.type,t,this.path)}return t}return e&&r&&e.markModified(this.path),this.cast([t],e,r)},r.prototype.castForQuery=function(t,e){var r,n;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Array.");n=r.call(this,e)}else{n=t;var i=this.casterConstructor.prototype,o=i.castForQuery||i.cast,s=this.caster;Array.isArray(n)?n=n.map(function(t){return o&&(t=o.call(s,t)),v(t)?t.toObject():t}):o&&(n=o.call(s,n))}return n&&v(n)?n.toObject():n};var b=r.prototype.$conditionalHandlers={};b.$all=u,b.$options=String,b.$elemMatch=f,b.$geoIntersects=c,b.$or=b.$and=function(t){if(!Array.isArray(t))throw new TypeError("conditional $or/$and require array");for(var e=[],r=0;r=r.valueOf()},message:r,type:"min"})}return this},r.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!=this.maxValidator},this)),t){var r=e||o.Date.max;r=r.replace(/{MAX}/,t===Date.now?"Date.now()":this.cast(t).toString());var n=this;this.validators.push({validator:this.maxValidator=function(e){var r=t===Date.now?t():n.cast(t);return null===e||e.valueOf()<=r.valueOf()},message:r,type:"max"})}return this},r.prototype.cast=function(t){if(null==t||""===t)return t;if(t instanceof Date)return t;var e;if("undefined"!=typeof t&&(t instanceof Number||"number"==typeof t||String(t)==Number(t)?e=new Date(Number(t)):t.toString&&(e=new Date(t.toString())),"Invalid Date"!=e.toString()))return e;throw new u("date",t,this.path)},r.prototype.$conditionalHandlers=s.options(a.prototype.$conditionalHandlers,{$all:i,$gt:n,$gte:n,$in:i,$lt:n,$lte:n,$ne:n,$nin:i}),r.prototype.castForQuery=function(t,e){var r;if(2!==arguments.length)return this.cast(t);if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Date.");return r.call(this,e)},e.exports=r},{"../error":8,"../schematype":30,"../utils":38}],24:[function(t,e){function r(t,e,r){function n(){a.apply(this,arguments)}n.prototype=Object.create(a.prototype),n.prototype.$__setSchema(e),n.schema=e;for(var s in e.methods)n.prototype[s]=e.methods[s];for(var s in e.statics)n[s]=e.statics[s];n.options=r,this.schema=e,i.call(this,t,n,r),this.schema=e;var u=this.path,f=this.defaultValue;this.default(function(){var t=f.call(this);return Array.isArray(t)||(t=[t]),new o(t,u,this)})}function n(t,e,r){if(!r||!e)return void 0;for(var n,i,o=t.path+".",s=Object.keys(e),a=s.length,u={};a--;)i=s[a],0===i.indexOf(o)&&(n||(n=!0),u[i.substring(o.length)]=e[i]);return n&&u||void 0}var i=t("./array"),o=(t("../document"),t("../types/documentarray")),s=t("../schematype"),a=t("../types/embedded");r.schemaName="DocumentArray",r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.doValidate=function(t,e,r){s.prototype.doValidate.call(this,t,function(r){if(r)return e(r);var n,i=t&&t.length;if(!i)return e();for(var o=0,s=i;s>o;++o){var a=t[o];a?a.validate(function(t){t&&(n=t),--i||e(n)}):--i||e(n)}},r)},r.prototype.doValidateSync=function(t,e){var r=s.prototype.doValidateSync.call(this,t,e);if(r)return r;var n=t&&t.length,i=null;if(n){for(var o=0,a=n;a>o&&!i;++o){var u=t[o];if(u){var f=u.validateSync();f&&(i=f)}}return i}},r.prototype.cast=function(t,e,r,i){var s,u,f;if(!Array.isArray(t))return e&&r&&e.markModified(this.path),this.cast([t],e,r,i);if((!t||!t.isMongooseDocumentArray)&&(t=new o(t,this.path,e),i&&i._handlers))for(var c in i._handlers)e.removeListener(c,i._handlers[c]);for(f=t.length;f--;)if(!(t[f]instanceof a)&&t[f])if(r)s||(s=n(this,e.$__.selected,r)),u=new this.casterConstructor(null,t,!0,s,f),t[f]=u.init(t[f]);else{try{u=i.id(t[f]._id)}catch(t){}i&&u?(u.set(t[f]),t[f]=u):(u=new this.casterConstructor(t[f],t,void 0,void 0,f),t[f]=u)}return t},e.exports=r},{"../document":4,"../schematype":30,"../types/documentarray":34,"../types/embedded":35,"./array":20}],25:[function(t,e,r){r.String=t("./string"),r.Number=t("./number"),r.Boolean=t("./boolean"),r.DocumentArray=t("./documentarray"),r.Array=t("./array"),r.Buffer=t("./buffer"),r.Date=t("./date"),r.ObjectId=t("./objectid"),r.Mixed=t("./mixed"),r.Oid=r.ObjectId,r.Object=r.Mixed,r.Bool=r.Boolean},{"./array":20,"./boolean":21,"./buffer":22,"./date":23,"./documentarray":24,"./mixed":26,"./number":27,"./objectid":28,"./string":29}],26:[function(t,e){function r(t,e){if(e&&e.default){var r=e.default;Array.isArray(r)&&0===r.length?e.default=Array:!e.shared&&i.isObject(r)&&0===Object.keys(r).length&&(e.default=function(){return{}})}n.call(this,t,e,"Mixed")}var n=t("../schematype"),i=t("../utils");r.schemaName="Mixed",r.prototype=Object.create(n.prototype),r.prototype.constructor=r,r.prototype.checkRequired=function(t){return void 0!==t&&null!==t},r.prototype.cast=function(t){return t},r.prototype.castForQuery=function(t,e){return 2===arguments.length?e:t},e.exports=r},{"../schematype":30,"../utils":38}],27:[function(t,e){(function(r){function n(t,e){a.call(this,t,e,"Number")}function i(t){return this.cast(t)}function o(t){var e=this;return t.map(function(t){return e.cast(t)})}var s,a=t("../schematype"),u=a.CastError,f=t("../error").messages,c=t("../utils");n.schemaName="Number",n.prototype=Object.create(a.prototype),n.prototype.constructor=n,n.prototype.checkRequired=function(t,e){return a._isRef(this,t,e,!0)?null!=t:"number"==typeof t||t instanceof Number},n.prototype.min=function(t,e){if(this.minValidator&&(this.validators=this.validators.filter(function(t){return t.validator!=this.minValidator},this)),null!=t){var r=e||f.Number.min;r=r.replace(/{MIN}/,t),this.validators.push({validator:this.minValidator=function(e){return null===e||e>=t},message:r,type:"min"})}return this},n.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!=this.maxValidator},this)),null!=t){var r=e||f.Number.max;r=r.replace(/{MAX}/,t),this.validators.push({validator:this.maxValidator=function(e){return null===e||t>=e},message:r,type:"max"})}return this},n.prototype.cast=function(e,n,i){if(a._isRef(this,e,n,i)){if(null==e)return e;if(s||(s=t("./../document")),e instanceof s)return e.$__.wasPopulated=!0,e;if("number"==typeof e)return e;if(r.isBuffer(e)||!c.isObject(e))throw new u("number",e,this.path);var o=n.$__fullPath(this.path),f=n.ownerDocument?n.ownerDocument():n,h=f.populated(o,!0),p=new h.options.model(e);return p.$__.wasPopulated=!0,p}var l=e&&e._id?e._id:e;if(!isNaN(l)){if(null===l)return l;if(""===l)return null;if("string"==typeof l&&(l=Number(l)),l instanceof Number)return l;if("number"==typeof l)return l;if(l.toString&&!Array.isArray(l)&&l.toString()==Number(l))return new Number(l)}throw new u("number",e,this.path)},n.prototype.$conditionalHandlers=c.options(a.prototype.$conditionalHandlers,{$all:o,$gt:i,$gte:i,$in:o,$lt:i,$lte:i,$ne:i,$mod:o,$nin:o}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Number.");return r.call(this,e)}return e=this.cast(t),null==e?e:e},e.exports=n}).call(this,t("buffer").Buffer)},{"../error":8,"../schematype":30,"../utils":38,"./../document":4,buffer:40}],28:[function(t,e){(function(r){function n(t,e){f.call(this,t,e,"ObjectID")}function i(t){return this.cast(t)}function o(t){var e=this;return t.map(function(t){return e.cast(t)})}function s(){return new h}function a(t){return this.$__._id=null,t}var u,f=t("../schematype"),c=f.CastError,h=t("../types/objectid"),p=t("../utils");n.schemaName="ObjectId",n.prototype=Object.create(f.prototype),n.prototype.constructor=n,n.prototype.auto=function(t){return t&&(this.default(s),this.set(a)),this},n.prototype.checkRequired=function(t,e){return f._isRef(this,t,e,!0)?null!=t:t instanceof h},n.prototype.cast=function(e,n,i){if(f._isRef(this,e,n,i)){if(null==e)return e;if(u||(u=t("./../document")),e instanceof u)return e.$__.wasPopulated=!0,e;if(e instanceof h)return e;if(r.isBuffer(e)||!p.isObject(e))throw new c("ObjectId",e,this.path);var o=n.$__fullPath(this.path),s=n.ownerDocument?n.ownerDocument():n,a=s.populated(o,!0),l=new a.options.model(e);return l.$__.wasPopulated=!0,l}if(null==e)return e;if(e instanceof h)return e;if(e._id){if(e._id instanceof h)return e._id;if(e._id.toString instanceof Function)try{return h.createFromHexString(e._id.toString())}catch(t){}}if(e.toString instanceof Function)try{return h.createFromHexString(e.toString())}catch(t){throw new c("ObjectId",e,this.path)}throw new c("ObjectId",e,this.path)},n.prototype.$conditionalHandlers=p.options(f.prototype.$conditionalHandlers,{$all:o,$gt:i,$gte:i,$in:o,$lt:i,$lte:i,$ne:i,$nin:o}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with ObjectId.");return r.call(this,e)}return this.cast(t)},e.exports=n}).call(this,t("buffer").Buffer)},{"../schematype":30,"../types/objectid":37,"../utils":38,"./../document":4,buffer:40}],29:[function(t,e){(function(r){function n(t,e){this.enumValues=[],this.regExp=null,a.call(this,t,e,"String")}function i(t){return this.castForQuery(t)}function o(t){var e=this;return t.map(function(t){return e.castForQuery(t)})}var s,a=t("../schematype"),u=a.CastError,f=t("../error").messages,c=t("../utils");n.schemaName="String",n.prototype=Object.create(a.prototype),n.prototype.constructor=n,n.prototype.enum=function(){if(this.enumValidator&&(this.validators=this.validators.filter(function(t){return t.validator!=this.enumValidator},this),this.enumValidator=!1),void 0===arguments[0]||!1===arguments[0])return this;var t,e;c.isObject(arguments[0])?(t=arguments[0].values,e=arguments[0].message):(t=arguments,e=f.String.enum);for(var r=0;r=t},message:r,type:"minlength"})}return this},n.prototype.maxlength=function(t,e){if(this.maxlengthValidator&&(this.validators=this.validators.filter(function(t){return t.validator!=this.maxlengthValidator},this)),null!=t){var r=e||f.String.maxlength;r=r.replace(/{MAXLENGTH}/,t),this.validators.push({validator:this.maxlengthValidator=function(e){return null===e||e.length<=t},message:r,type:"maxlength"})}return this},n.prototype.match=function(t,e){var r=e||f.String.match,n=function(e){var r=null!=e&&""!==e?t.test(e):!0;return r};return this.validators.push({validator:n,message:r,type:"regexp"}),this},n.prototype.checkRequired=function(t,e){return a._isRef(this,t,e,!0)?null!=t:(t instanceof String||"string"==typeof t)&&t.length},n.prototype.cast=function(e,n,i){if(a._isRef(this,e,n,i)){if(null==e)return e;if(s||(s=t("./../document")),e instanceof s)return e.$__.wasPopulated=!0,e;if("string"==typeof e)return e;if(r.isBuffer(e)||!c.isObject(e))throw new u("string",e,this.path);var o=n.$__fullPath(this.path),f=n.ownerDocument?n.ownerDocument():n,h=f.populated(o,!0),p=new h.options.model(e);return p.$__.wasPopulated=!0,p}if(null==e)return e;if("undefined"!=typeof e){if(e._id&&"string"==typeof e._id)return e._id;if(e.toString)return e.toString()}throw new u("string",e,this.path)},n.prototype.$conditionalHandlers=c.options(a.prototype.$conditionalHandlers,{$all:o,$gt:i,$gte:i,$in:o,$lt:i,$lte:i,$ne:i,$nin:o,$options:i,$regex:i}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with String.");return r.call(this,e)}return e=t,e instanceof RegExp?e:this.cast(e)},e.exports=n}).call(this,t("buffer").Buffer)},{"../error":8,"../schematype":30,"../utils":38,"./../document":4,buffer:40}],30:[function(t,e,r){(function(n){function i(t,e,r){this.path=t,this.instance=r,this.validators=[],this.setters=[],this.getters=[],this.options=e,this._index=null,this.selected;for(var n in e)if(this[n]&&"function"==typeof this[n]){if("index"==n&&this._index)continue;var i=Array.isArray(e[n])?e[n]:[e[n]];this[n].apply(this,i)}}function o(t){return this.cast(t)}var s=t("./utils"),a=t("./error"),u=a.messages,f=a.CastError,c=a.ValidatorError;i.prototype.default=function(t){return 1===arguments.length?(this.defaultValue="function"==typeof t?t:this.cast(t),this):(arguments.length>1&&(this.defaultValue=s.args(arguments)),this.defaultValue)},i.prototype.index=function(t){return this._index=t,s.expires(this._index),this},i.prototype.unique=function(t){return null==this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.unique=t,this},i.prototype.text=function(t){return null==this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.text=t,this},i.prototype.sparse=function(t){return null==this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.sparse=t,this},i.prototype.set=function(t){if("function"!=typeof t)throw new TypeError("A setter must be a function.");return this.setters.push(t),this},i.prototype.get=function(t){if("function"!=typeof t)throw new TypeError("A getter must be a function.");return this.getters.push(t),this},i.prototype.validate=function(t,e,r){if("function"==typeof t||t&&"RegExp"===s.getFunctionName(t.constructor)){var n;return e instanceof Object&&!r?(n=s.clone(e),n.message||(n.message=n.msg),n.validator=t):(e||(e=u.general.default),r||(r="user defined"),n={message:e,type:r,validator:t}),this.validators.push(n),this}var i,o,a;for(i=0,o=arguments.length;o>i;i++){if(a=arguments[i],!a||"Object"!==s.getFunctionName(a.constructor)){var f="Invalid validator. Received ("+typeof a+") "+a+". See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate";throw new Error(f)}this.validate(a.validator,a)}return this},i.prototype.required=function(t,e){if(!1===t)return this.validators=this.validators.filter(function(t){return t.validator!=this.requiredValidator},this),this.isRequired=!1,this;var r=this;this.isRequired=!0,this.requiredValidator=function(e){return"isSelected"in this&&!this.isSelected(r.path)&&!this.isModified(r.path)?!0:"function"==typeof t&&!t.apply(this)||r.checkRequired(e,this)},"string"==typeof t&&(e=t,t=void 0);var n=e||u.general.required;return this.validators.unshift({validator:this.requiredValidator,message:n,type:"required"}),this},i.prototype.getDefault=function(t,e){var r="function"==typeof this.defaultValue?this.defaultValue.call(t):this.defaultValue;return null!==r&&void 0!==r?this.cast(r,t,e):r},i.prototype.applySetters=function(t,e,r,n){for(var i=t,o=this.setters,s=o.length,a=this.caster;s--;)i=o[s].call(e,i,this);if(Array.isArray(i)&&a&&a.setters){for(var u=[],f=0;fr?arguments[r]:this._cast(arguments[r],arguments[0]+(r-2));t=[].splice.apply(this,e),this._registerAtomic("$set",this),this._markModified()}return t},unshift:function(){var t=[].map.call(arguments,this._cast,this);return[].unshift.apply(this,t),this._registerAtomic("$set",this),this._markModified(),this.length},sort:function(){var t=[].sort.apply(this,arguments);return this._registerAtomic("$set",this),this._markModified(),t},addToSet:function(){var t=[].map.call(arguments,this._mapCast,this),e=[],r=t[0]instanceof o?"doc":t[0]instanceof Date?"date":"";return t.forEach(function(t){var n;switch(r){case"doc":n=this.some(function(e){return e.equals(t)});break;case"date":var i=+t;n=this.some(function(t){return+t===i});break;default:n=~this.indexOf(t)}n||([].push.call(this,t),this._registerAtomic("$addToSet",t),this._markModified(),[].push.call(e,t))},this),e},set:function(t,e){return this[t]=this._cast(e,t),this._markModified(t),this},toObject:function(t){return t&&t.depopulate?this.map(function(e){return e instanceof s?e.toObject(t):e}):this.slice()},inspect:function(){return JSON.stringify(this)},indexOf:function(t){t instanceof a&&(t=t.toString());for(var e=0,r=this.length;r>e;++e)if(t==this[e])return e;return-1}},i.mixin.remove=i.mixin.pull,e.exports=r=i}).call(this,t("buffer").Buffer)},{"../document":4,"../utils":38,"./embedded":35,"./objectid":37,buffer:40}],33:[function(t,e){(function(r,n){function i(t,e,r){var o,a=arguments.length;o=0===a||null===arguments[0]||void 0===arguments[0]?0:t;var u,f,c;Array.isArray(e)?(f=e[0],c=e[1]):u=e;var h=new n(o,u,r);return s.decorate(h,i.mixin),h.isMongooseBuffer=!0,Object.defineProperties(h,{validators:{value:[]},_path:{value:f},_parent:{value:c}}),c&&"string"==typeof f&&Object.defineProperty(h,"_schema",{value:c.schema.path(f)}),h._subtype=0,h}var o=(r.MONGOOSE_DRIVER_PATH||"../drivers/node-mongodb-native",t("../drivers/node-mongodb-native/binary")),s=t("../utils");i.mixin={_parent:void 0,_subtype:void 0,_markModified:function(){var t=this._parent;return t&&t.markModified(this._path),this},write:function(){var t=n.prototype.write.apply(this,arguments);return t>0&&this._markModified(),t},copy:function(t){var e=n.prototype.copy.apply(this,arguments);return t&&t.isMongooseBuffer&&t._markModified(),e}},"writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 writeFloat writeDouble fill utf8Write binaryWrite asciiWrite set writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE writeInt16LE writeInt16BE writeInt32LE writeInt32BE writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE".split(" ").forEach(function(t){n.prototype[t]&&(i.mixin[t]=new Function("var ret = Buffer.prototype."+t+".apply(this, arguments);this._markModified();return ret;"))}),i.mixin.toObject=function(t){var e="number"==typeof t?t:this._subtype||0;return new o(this,e)},i.mixin.equals=function(t){if(!n.isBuffer(t))return!1;if(this.length!==t.length)return!1;for(var e=0;ea;a++)if(n=this[a].get("_id"),n instanceof f){if(r||(r=String(t)),r==n._id)return this[a]}else if(n instanceof o){if(e==n)return this[a]}else if(r||(r=String(t)),r==n)return this[a];return null},n.mixin.toObject=function(t){return this.map(function(e){return e&&e.toObject(t)||null})},n.mixin.inspect=function(){return"["+Array.prototype.map.call(this,function(t){return t?t.inspect?t.inspect():u.inspect(t):"null"}).join("\n")+"]"},n.mixin.create=function(t){return new this._schema.casterConstructor(t)},n.mixin.notify=function(t){var e=this;return function(r){for(var n=e.length;n--;)if(e[n]){switch(t){case"save":r=e[n]}e[n].emit(t,r)}}},e.exports=n}).call(this,t("buffer").Buffer)},{"../document":4,"../schema/objectid":28,"../utils":38,"./array":32,"./objectid":37,buffer:40,util:48}],35:[function(t,e){function r(t,e,r,n,o){e?(this.__parentArray=e,this.__parent=e._parent):(this.__parentArray=void 0,this.__parent=void 0),this.__index=o,i.call(this,t,n,r);var s=this;this.on("isNew",function(t){s.isNew=t})}function n(t){function e(){r.removeListener("save",e),r.removeListener("remove",e),t.emit("remove",t),r=t=e=null}var r=t.ownerDocument();r.on("save",e),r.on("remove",e)}var i=t("../document_provider")(),o=t("util").inspect,s=t("../promise");r.prototype=Object.create(i.prototype),r.prototype.constructor=r,r.prototype.markModified=function(t){this.__parentArray&&(this.$__.activePaths.modify(t),this.isNew?this.__parentArray._markModified():this.__parentArray._markModified(this,t))},r.prototype.save=function(t){var e=new s(t);return e.fulfill(),e},r.prototype.remove=function(t){if(!this.__parentArray)return this;var e;if(!this.willRemove){if(e=this._doc._id,!e)throw new Error("For your own good, Mongoose does not know how to remove an EmbeddedDocument that has no _id");this.__parentArray.pull({_id:e}),this.willRemove=!0,n(this)}return t&&t(null),this},r.prototype.update=function(){throw new Error("The #update method is not available on EmbeddedDocuments")},r.prototype.inspect=function(){return o(this.toObject())},r.prototype.invalidate=function(t,e,r,n){if(!this.__parent){var i="Unable to invalidate a subdocument that has not been added to an array.";throw new Error(i)}var o=this.__index;if("undefined"!=typeof o){var s=this.__parentArray._path,a=[s,o,t].join(".");this.__parent.invalidate(a,e,r)}return n&&(this.$__.validationError=this.ownerDocument().$__.validationError),!0},r.prototype.$markValid=function(t){if(this.__parent){var e=this.__index;if("undefined"!=typeof e){var r=this.__parentArray._path,n=[r,e,t].join(".");this.__parent.$markValid(n)}}},r.prototype.$isValid=function(t){var e=this.__index;if("undefined"!=typeof e){{var r=this.__parentArray._path;[r,e,t].join(".")}return!this.__parent.$__.validationError||!this.__parent.$__.validationError.errors[t]}return!0},r.prototype.ownerDocument=function(){if(this.$__.ownerDocument)return this.$__.ownerDocument;var t=this.__parent;if(!t)return this;for(;t.__parent;)t=t.__parent;return this.$__.ownerDocument=t},r.prototype.$__fullPath=function(t){if(!this.$__.fullPath){var e=this;if(!e.__parent)return t;for(var r=[];e.__parent;)r.unshift(e.__parentArray._path),e=e.__parent;this.$__.fullPath=r.join("."),this.$__.ownerDocument||(this.$__.ownerDocument=e)}return t?this.$__.fullPath+"."+t:this.$__.fullPath},r.prototype.parent=function(){return this.__parent},r.prototype.parentArray=function(){return this.__parentArray},e.exports=r},{"../document_provider":5,"../promise":18,util:48}],36:[function(t,e,r){r.Array=t("./array"),r.Buffer=t("./buffer"),r.Document=r.Embedded=t("./embedded"),r.DocumentArray=t("./documentarray"),r.ObjectId=t("./objectid")},{"./array":32,"./buffer":33,"./documentarray":34,"./embedded":35,"./objectid":37}],37:[function(t,e){(function(r){var n=(r.MONGOOSE_DRIVER_PATH||"../drivers/node-mongodb-native",t("../drivers/node-mongodb-native/objectid"));e.exports=n}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../drivers/node-mongodb-native/objectid":7}],38:[function(t,e,r){(function(e,n){function i(t){var e;return!~v.indexOf(t.toLowerCase())&&(e=m.filter(function(e){return t.match(e[0])}),e[0])?t.replace(e[0][0],e[0][1]):t}function o(t,e){var r,n,i,o,s,a=e&&e.retainKeyOrder,u=e&&e.minimize,f={};if(a)for(o in t)i=b(t[o],e),u&&"undefined"==typeof i||(r||(r=!0),f[o]=i);else for(n=Object.keys(t),s=n.length;s--;)o=n[s],i=b(t[o],e),u&&"undefined"==typeof i||(r||(r=!0),f[o]=i);return u?r&&f:f}function s(t,e){for(var r=[],n=0,i=t.length;i>n;n++)r.push(b(t[n],e));return r}function a(t,e,r,n,i){this.path=t,this.match=r,this.select=e,this.options=n,this.model=i,this._docs={}}var u,f,c,h=t("mongodb"),p=t("./types/objectid"),l=t("regexp-clone"),d=t("sliced"),y=t("mpath"),g=t("ms"),_=h?h.ReadPreference:function(t){return t};r.toCollectionName=function(t,e){return e=e||{},"system.profile"===t?t:"system.indexes"===t?t:e.pluralization===!1?t:i(t.toLowerCase())},r.pluralization=[[/(m)an$/gi,"$1en"],[/(pe)rson$/gi,"$1ople"],[/(child)$/gi,"$1ren"],[/^(ox)$/gi,"$1en"],[/(ax|test)is$/gi,"$1es"],[/(octop|vir)us$/gi,"$1i"],[/(alias|status)$/gi,"$1es"],[/(bu)s$/gi,"$1ses"],[/(buffal|tomat|potat)o$/gi,"$1oes"],[/([ti])um$/gi,"$1a"],[/sis$/gi,"ses"],[/(?:([^f])fe|([lr])f)$/gi,"$1$2ves"],[/(hive)$/gi,"$1s"],[/([^aeiouy]|qu)y$/gi,"$1ies"],[/(x|ch|ss|sh)$/gi,"$1es"],[/(matr|vert|ind)ix|ex$/gi,"$1ices"],[/([m|l])ouse$/gi,"$1ice"],[/(kn|w|l)ife$/gi,"$1ives"],[/(quiz)$/gi,"$1zes"],[/s$/gi,"s"],[/([^a-z])$/,"$1"],[/$/gi,"s"]];var m=r.pluralization;r.uncountables=["advice","energy","excretion","digestion","cooperation","health","justice","labour","machinery","equipment","information","pollution","sewage","paper","money","species","series","rain","rice","fish","sheep","moose","deer","news","expertise","status","media"];var v=r.uncountables;r.deepEqual=function t(e,i){if(e===i)return!0;if(e instanceof Date&&i instanceof Date)return e.getTime()===i.getTime();if(e instanceof p&&i instanceof p)return e.toString()===i.toString();if(e instanceof RegExp&&i instanceof RegExp)return e.source==i.source&&e.ignoreCase==i.ignoreCase&&e.multiline==i.multiline&&e.global==i.global;if("object"!=typeof e&&"object"!=typeof i)return e==i;if(null===e||null===i||void 0===e||void 0===i)return!1;if(e.prototype!==i.prototype)return!1;if(e instanceof Number&&i instanceof Number)return e.valueOf()===i.valueOf();if(n.isBuffer(e))return r.buffer.areEqual(e,i);O(e)&&(e=e.toObject()),O(i)&&(i=i.toObject());try{var o,s,a=Object.keys(e),u=Object.keys(i)}catch(t){return!1}if(a.length!=u.length)return!1;for(a.sort(),u.sort(),s=a.length-1;s>=0;s--)if(a[s]!=u[s])return!1;for(s=a.length-1;s>=0;s--)if(o=a[s],!t(e[o],i[o]))return!1;return!0},r.clone=function(t,e){if(void 0===t||null===t)return t;if(Array.isArray(t))return s(t,e);if(O(t))return e&&e.json&&"function"==typeof t.toJSON?t.toJSON(e):t.toObject(e);if(t.constructor)switch(r.getFunctionName(t.constructor)){case"Object":return o(t,e);case"Date":return new t.constructor(+t);case"RegExp":return l(t)}return t instanceof p?new p(t.id):!t.constructor&&r.isObject(t)?o(t,e):t.valueOf?t.valueOf():void 0};var b=r.clone;r.options=function(t,e){var r,n=Object.keys(t),i=n.length;for(e=e||{};i--;)r=n[i],r in e||(e[r]=t[r]);return e},r.random=function(){return Math.random().toString().substr(3)},r.merge=function t(e,n){for(var i,o=Object.keys(n),s=o.length;s--;)i=o[s],"undefined"==typeof e[i]?e[i]=n[i]:r.isObject(n[i])&&t(e[i],n[i])};var w=Object.prototype.toString;r.isObject=function(t){return"[object Object]"==w.call(t)},r.args=d,r.tick=function(t){return"function"==typeof t?function(){try{t.apply(this,arguments)}catch(t){e.nextTick(function(){throw t})}}:void 0},r.isMongooseObject=function(e){return c||(c=t("./document")),f||(f=t("./types").Array),u||(u=t("./types").Buffer),e instanceof c||e&&e.isMongooseArray||e&&e.isMongooseBuffer};var O=r.isMongooseObject;r.expires=function(t){if(t&&"Object"==t.constructor.name&&"expires"in t){var e;e="string"!=typeof t.expires?t.expires:Math.round(g(t.expires)/1e3),t.expireAfterSeconds=e,delete t.expires}},r.readPref=function(t,e){if(Array.isArray(t)&&(e=t[1],t=t[0]),t instanceof _)return t;switch(t){case"p":t="primary";break;case"pp":t="primaryPreferred";break;case"s":t="secondary";break;case"sp":t="secondaryPreferred";break;case"n":t="nearest"}return new _(t,e)},a.prototype.constructor=Object,r.PopulateOptions=a,r.populate=function(t,e,n,i,o){if(1===arguments.length){if(t instanceof a)return[t];if(Array.isArray(t))return t.map(function(t){return r.populate(t)[0]});r.isObject(t)&&(i=t.match,o=t.options,e=t.select,n=t.model,t=t.path)}else"string"!=typeof n&&"function"!=typeof n&&(o=i,i=n,n=void 0);if("string"!=typeof t)throw new TypeError("utils.populate: invalid path. Expected string. Got typeof `"+typeof t+"`");for(var s=[],u=t.split(" "),f=0;fo;++o)if("number"==typeof t[o]||"string"==typeof t[o]){if(e[t[o]])continue;n.push(t[o]),e[t[o]]=!0}else if(t[o]instanceof p){if(r[t[o].toString()])continue;n.push(t[o]),r[t[o].toString()]=!0}else n.push(t[o]);return n},r.buffer={},r.buffer.areEqual=function(t,e){if(!n.isBuffer(t))return!1;if(!n.isBuffer(e))return!1;if(t.length!==e.length)return!1;for(var r=0,i=t.length;i>r;++r)if(t[r]!==e[r])return!1;return!0},r.getFunctionName=function(t){return t.name?t.name:(t.toString().trim().match(/^function\s*([^\s(]+)/)||[])[1]},r.decorate=function(t,e){for(var r in e)t[r]=e[r]},r.mergeClone=function(t,e){for(var n,i=Object.keys(e),o=i.length;o--;)n=i[o],"undefined"==typeof t[n]?t[n]=r.clone(e[n],{retainKeyOrder:1}):r.isObject(e[n])?r.mergeClone(t[n],e[n]):t[n]=r.clone(e[n],{retainKeyOrder:1})},r.each=function(t,e){for(var r=0;r=0;n--)r=this.getters[n].call(e,r,this);return r},r.prototype.applySetters=function(t,e){for(var r=t,n=this.setters.length-1;n>=0;n--)r=this.setters[n].call(e,r,this);return r},e.exports=r},{}],40:[function(t,e,r){function n(t,e,r){if(!(this instanceof n))return new n(t,e,r);var i,o=typeof t;if("number"===o)i=t>0?t>>>0:0;else if("string"===o)"base64"===e&&(t=B(t)),i=n.byteLength(t,e);else{if("object"!==o||null===t)throw new TypeError("must start with number, buffer, array or string");"Buffer"===t.type&&L(t.data)&&(t=t.data),i=+t.length>0?Math.floor(+t.length):0}if(this.length>R)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+R.toString(16)+" bytes");var s;n.TYPED_ARRAY_SUPPORT?s=n._augment(new Uint8Array(i)):(s=this,s.length=i,s._isBuffer=!0);var a;if(n.TYPED_ARRAY_SUPPORT&&"number"==typeof t.byteLength)s._set(t);else if(E(t))if(n.isBuffer(t))for(a=0;i>a;a++)s[a]=t.readUInt8(a);else for(a=0;i>a;a++)s[a]=(t[a]%256+256)%256;else if("string"===o)s.write(t,0,e);else if("number"===o&&!n.TYPED_ARRAY_SUPPORT&&!r)for(a=0;i>a;a++)s[a]=0;return s}function i(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;if(o%2!==0)throw new Error("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;n>s;s++){var a=parseInt(e.substr(2*s,2),16);if(isNaN(a))throw new Error("Invalid hex string");t[r+s]=a}return s}function o(t,e,r,n){var i=j(N(e),t,r,n);return i}function s(t,e,r,n){var i=j(T(e),t,r,n);return i}function a(t,e,r,n){return s(t,e,r,n)}function u(t,e,r,n){var i=j(x(e),t,r,n);return i}function f(t,e,r,n){var i=j($(e),t,r,n,2);return i}function c(t,e,r){return I.fromByteArray(0===e&&r===t.length?t:t.slice(e,r))}function h(t,e,r){var n="",i="";r=Math.min(t.length,r);for(var o=e;r>o;o++)t[o]<=127?(n+=D(i)+String.fromCharCode(t[o]),i=""):i+="%"+t[o].toString(16);return n+D(i)}function p(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function l(t,e,r){return p(t,e,r)}function d(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",o=e;r>o;o++)i+=S(t[o]);return i}function y(t,e,r){for(var n=t.slice(e,r),i="",o=0;ot)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function _(t,e,r,i,o,s){if(!n.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>o||s>e)throw new TypeError("value is out of bounds");if(r+i>t.length)throw new TypeError("index out of range")}function m(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);o>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function v(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);o>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function b(t,e,r,n,i,o){if(e>i||o>e)throw new TypeError("value is out of bounds");if(r+n>t.length)throw new TypeError("index out of range")}function w(t,e,r,n,i){return i||b(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),M.write(t,e,r,n,23,4),r+4}function O(t,e,r,n,i){return i||b(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),M.write(t,e,r,n,52,8),r+8}function B(t){for(t=A(t).replace(k,"");t.length%4!==0;)t+="=";return t}function A(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function E(t){return L(t)||n.isBuffer(t)||t&&"object"==typeof t&&"number"==typeof t.length}function S(t){return 16>t?"0"+t.toString(16):t.toString(16)}function N(t){for(var e=[],r=0;r=n)e.push(n);else{var i=r;n>=55296&&57343>=n&&r++;for(var o=encodeURIComponent(t.slice(i,r+1)).substr(1).split("%"),s=0;s>8,n=e%256,i.push(n),i.push(r);return i}function x(t){return I.toByteArray(t)}function j(t,e,r,n,i){i&&(n-=n%i);for(var o=0;n>o&&!(o+r>=e.length||o>=t.length);o++)e[o+r]=t[o];return o}function D(t){try{return decodeURIComponent(t)}catch(t){return String.fromCharCode(65533)}}var I=t("base64-js"),M=t("ieee754"),L=t("is-array");r.Buffer=n,r.SlowBuffer=n,r.INSPECT_MAX_BYTES=50,n.poolSize=8192;var R=1073741823;n.TYPED_ARRAY_SUPPORT=function(){try{var t=new ArrayBuffer(0),e=new Uint8Array(t);return e.foo=function(){return 42},42===e.foo()&&"function"==typeof e.subarray&&0===new Uint8Array(1).subarray(1,1).byteLength}catch(t){return!1}}(),n.isBuffer=function(t){return!(null==t||!t._isBuffer)},n.compare=function(t,e){if(!n.isBuffer(t)||!n.isBuffer(e))throw new TypeError("Arguments must be Buffers");for(var r=t.length,i=e.length,o=0,s=Math.min(r,i);s>o&&t[o]===e[o];o++);return o!==s&&(r=t[o],i=e[o]),i>r?-1:r>i?1:0},n.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(t,e){if(!L(t))throw new TypeError("Usage: Buffer.concat(list[, length])");if(0===t.length)return new n(0);if(1===t.length)return t[0];var r;if(void 0===e)for(e=0,r=0;r>>1;break;case"utf8":case"utf-8":r=N(t).length;break;case"base64":r=x(t).length;break;default:r=t.length}return r},n.prototype.length=void 0,n.prototype.parent=void 0,n.prototype.toString=function(t,e,r){var n=!1;if(e>>>=0,r=void 0===r||1/0===r?this.length:r>>>0,t||(t="utf8"),0>e&&(e=0),r>this.length&&(r=this.length),e>=r)return"";for(;;)switch(t){case"hex":return d(this,e,r);case"utf8":case"utf-8":return h(this,e,r);case"ascii":return p(this,e,r);case"binary":return l(this,e,r);case"base64":return c(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return y(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}},n.prototype.equals=function(t){if(!n.isBuffer(t))throw new TypeError("Argument must be a Buffer");return 0===n.compare(this,t)},n.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},n.prototype.compare=function(t){if(!n.isBuffer(t))throw new TypeError("Argument must be a Buffer");return n.compare(this,t)},n.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},n.prototype.set=function(t,e){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,e)},n.prototype.write=function(t,e,r,n){if(isFinite(e))isFinite(r)||(n=r,r=void 0);else{var c=n;n=e,e=r,r=c}e=Number(e)||0;var h=this.length-e;r?(r=Number(r),r>h&&(r=h)):r=h,n=String(n||"utf8").toLowerCase();var p;switch(n){case"hex":p=i(this,t,e,r);break;case"utf8":case"utf-8":p=o(this,t,e,r);break;case"ascii":p=s(this,t,e,r);break;case"binary":p=a(this,t,e,r);break;case"base64":p=u(this,t,e,r);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":p=f(this,t,e,r);break;default:throw new TypeError("Unknown encoding: "+n)}return p},n.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},n.prototype.slice=function(t,e){var r=this.length;if(t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t),n.TYPED_ARRAY_SUPPORT)return n._augment(this.subarray(t,e));for(var i=e-t,o=new n(i,void 0,!0),s=0;i>s;s++)o[s]=this[s+t];return o},n.prototype.readUInt8=function(t,e){return e||g(t,1,this.length),this[t]},n.prototype.readUInt16LE=function(t,e){return e||g(t,2,this.length),this[t]|this[t+1]<<8},n.prototype.readUInt16BE=function(t,e){return e||g(t,2,this.length),this[t]<<8|this[t+1]},n.prototype.readUInt32LE=function(t,e){return e||g(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},n.prototype.readUInt32BE=function(t,e){return e||g(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},n.prototype.readInt8=function(t,e){return e||g(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},n.prototype.readInt16LE=function(t,e){e||g(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt16BE=function(t,e){e||g(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt32LE=function(t,e){return e||g(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},n.prototype.readInt32BE=function(t,e){return e||g(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},n.prototype.readFloatLE=function(t,e){return e||g(t,4,this.length),M.read(this,t,!0,23,4)},n.prototype.readFloatBE=function(t,e){return e||g(t,4,this.length),M.read(this,t,!1,23,4)},n.prototype.readDoubleLE=function(t,e){return e||g(t,8,this.length),M.read(this,t,!0,52,8)},n.prototype.readDoubleBE=function(t,e){return e||g(t,8,this.length),M.read(this,t,!1,52,8)},n.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,1,255,0),n.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=t,e+1},n.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,2,65535,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8):m(this,t,e,!0),e+2},n.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,2,65535,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=t):m(this,t,e,!1),e+2},n.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,4,4294967295,0),n.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=t):v(this,t,e,!0),e+4},n.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,4,4294967295,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t):v(this,t,e,!1),e+4},n.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,1,127,-128),n.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=t,e+1},n.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,2,32767,-32768),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8):m(this,t,e,!0),e+2},n.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,2,32767,-32768),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=t):m(this,t,e,!1),e+2},n.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,4,2147483647,-2147483648),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):v(this,t,e,!0),e+4},n.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||_(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t):v(this,t,e,!1),e+4},n.prototype.writeFloatLE=function(t,e,r){return w(this,t,e,!0,r)},n.prototype.writeFloatBE=function(t,e,r){return w(this,t,e,!1,r)},n.prototype.writeDoubleLE=function(t,e,r){return O(this,t,e,!0,r)},n.prototype.writeDoubleBE=function(t,e,r){return O(this,t,e,!1,r)},n.prototype.copy=function(t,e,r,i){var o=this;if(r||(r=0),i||0===i||(i=this.length),e||(e=0),i!==r&&0!==t.length&&0!==o.length){if(r>i)throw new TypeError("sourceEnd < sourceStart");if(0>e||e>=t.length)throw new TypeError("targetStart out of bounds");if(0>r||r>=o.length)throw new TypeError("sourceStart out of bounds");if(0>i||i>o.length)throw new TypeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-es||!n.TYPED_ARRAY_SUPPORT)for(var a=0;s>a;a++)t[a+e]=this[a+r];else t._set(this.subarray(r,r+s),e)}},n.prototype.fill=function(t,e,r){if(t||(t=0),e||(e=0),r||(r=this.length),e>r)throw new TypeError("end < start");if(r!==e&&0!==this.length){if(0>e||e>=this.length)throw new TypeError("start out of bounds");if(0>r||r>this.length)throw new TypeError("end out of bounds");var n;if("number"==typeof t)for(n=e;r>n;n++)this[n]=t;else{var i=N(t.toString()),o=i.length;for(n=e;r>n;n++)this[n]=i[n%o]}return this}},n.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(n.TYPED_ARRAY_SUPPORT)return new n(this).buffer;for(var t=new Uint8Array(this.length),e=0,r=t.length;r>e;e+=1)t[e]=this[e];return t.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var P=n.prototype;n._augment=function(t){return t.constructor=n,t._isBuffer=!0,t._get=t.get,t._set=t.set,t.get=P.get,t.set=P.set,t.write=P.write,t.toString=P.toString,t.toLocaleString=P.toString,t.toJSON=P.toJSON,t.equals=P.equals,t.compare=P.compare,t.copy=P.copy,t.slice=P.slice,t.readUInt8=P.readUInt8,t.readUInt16LE=P.readUInt16LE,t.readUInt16BE=P.readUInt16BE,t.readUInt32LE=P.readUInt32LE,t.readUInt32BE=P.readUInt32BE,t.readInt8=P.readInt8,t.readInt16LE=P.readInt16LE,t.readInt16BE=P.readInt16BE,t.readInt32LE=P.readInt32LE,t.readInt32BE=P.readInt32BE,t.readFloatLE=P.readFloatLE,t.readFloatBE=P.readFloatBE,t.readDoubleLE=P.readDoubleLE,t.readDoubleBE=P.readDoubleBE,t.writeUInt8=P.writeUInt8,t.writeUInt16LE=P.writeUInt16LE,t.writeUInt16BE=P.writeUInt16BE,t.writeUInt32LE=P.writeUInt32LE,t.writeUInt32BE=P.writeUInt32BE,t.writeInt8=P.writeInt8,t.writeInt16LE=P.writeInt16LE,t.writeInt16BE=P.writeInt16BE,t.writeInt32LE=P.writeInt32LE,t.writeInt32BE=P.writeInt32BE,t.writeFloatLE=P.writeFloatLE,t.writeFloatBE=P.writeFloatBE,t.writeDoubleLE=P.writeDoubleLE,t.writeDoubleBE=P.writeDoubleBE,t.fill=P.fill,t.inspect=P.inspect,t.toArrayBuffer=P.toArrayBuffer,t};var k=/[^+\/0-9A-z]/g},{"base64-js":41,ieee754:42,"is-array":43}],41:[function(t,e,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(t){"use strict";function e(t){var e=t.charCodeAt(0);return e===s?62:e===a?63:u>e?-1:u+10>e?e-u+26+26:c+26>e?e-c:f+26>e?e-f+26:void 0}function r(t){function r(t){f[h++]=t}var n,i,s,a,u,f;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var c=t.length;u="="===t.charAt(c-2)?2:"="===t.charAt(c-1)?1:0,f=new o(3*t.length/4-u),s=u>0?t.length-4:t.length;var h=0;for(n=0,i=0;s>n;n+=4,i+=3)a=e(t.charAt(n))<<18|e(t.charAt(n+1))<<12|e(t.charAt(n+2))<<6|e(t.charAt(n+3)),r((16711680&a)>>16),r((65280&a)>>8),r(255&a);return 2===u?(a=e(t.charAt(n))<<2|e(t.charAt(n+1))>>4,r(255&a)):1===u&&(a=e(t.charAt(n))<<10|e(t.charAt(n+1))<<4|e(t.charAt(n+2))>>2,r(a>>8&255),r(255&a)),f}function i(t){function e(t){return n.charAt(t)}function r(t){return e(t>>18&63)+e(t>>12&63)+e(t>>6&63)+e(63&t)}var i,o,s,a=t.length%3,u="";for(i=0,s=t.length-a;s>i;i+=3)o=(t[i]<<16)+(t[i+1]<<8)+t[i+2],u+=r(o);switch(a){case 1:o=t[t.length-1],u+=e(o>>2),u+=e(o<<4&63),u+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],u+=e(o>>10),u+=e(o>>4&63),u+=e(o<<2&63),u+="="}return u}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),a="/".charCodeAt(0),u="0".charCodeAt(0),f="a".charCodeAt(0),c="A".charCodeAt(0);t.toByteArray=r,t.fromByteArray=i}("undefined"==typeof r?this.base64js={}:r)},{}],42:[function(t,e,r){r.read=function(t,e,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,l=t[e+h];for(h+=p,o=l&(1<<-c)-1,l>>=-c,c+=a;c>0;o=256*o+t[e+h],h+=p,c-=8);for(s=o&(1<<-c)-1,o>>=-c,c+=n;c>0;s=256*s+t[e+h],h+=p,c-=8);if(0===o)o=1-f;else{if(o===u)return s?0/0:1/0*(l?-1:1);s+=Math.pow(2,n),o-=f}return(l?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var s,a,u,f=8*o-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:o-1,d=n?1:-1,y=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||1/0===e?(a=isNaN(e)?1:0,s=c):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),e+=s+h>=1?p/u:p*Math.pow(2,1-h),e*u>=2&&(s++,u/=2),s+h>=c?(a=0,s=c):s+h>=1?(a=(e*u-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[r+l]=255&a,l+=d,a/=256,i-=8);for(s=s<0;t[r+l]=255&s,l+=d,s/=256,f-=8);t[r+l-d]|=128*y}},{}],43:[function(t,e){var r=Array.isArray,n=Object.prototype.toString;e.exports=r||function(t){return!!t&&"[object Array]"==n.call(t)}},{}],44:[function(t,e){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(t){return"function"==typeof t}function i(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(t){if(!i(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this -},r.prototype.emit=function(t){var e,r,i,a,u,f;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];r.apply(this,a)}else if(o(r)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(f=r.slice(),i=f.length,u=0;i>u;u++)f[u].apply(this,a)}return!0},r.prototype.addListener=function(t,e){var i;if(!n(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,n(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned){var i;i=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,s,a;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],s=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(a=s;a-->0;)if(r[a]===e||r[a].listener&&r[a].listener===e){i=a;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?n(t._events[e])?1:t._events[e].length:0}},{}],45:[function(t,e){e.exports="function"==typeof Object.create?function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],46:[function(t,e){function r(){}var n=e.exports={};n.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var r=[];return window.addEventListener("message",function(t){var e=t.source;if((e===window||null===e)&&"process-tick"===t.data&&(t.stopPropagation(),r.length>0)){var n=r.shift();n()}},!0),function(t){r.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=r,n.addListener=r,n.once=r,n.off=r,n.removeListener=r,n.removeAllListeners=r,n.emit=r,n.binding=function(){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw new Error("process.chdir is not supported")}},{}],47:[function(t,e){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],48:[function(t,e,r){(function(e,n){function i(t,e){var n={seen:[],stylize:s};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),y(e)?n.showHidden=e:e&&r._extend(n,e),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),u(n,t,n.depth)}function o(t,e){var r=i.styles[e];return r?"["+i.colors[r][0]+"m"+t+"["+i.colors[r][1]+"m":t}function s(t){return t}function a(t){var e={};return t.forEach(function(t){e[t]=!0}),e}function u(t,e,n){if(t.customInspect&&e&&S(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return v(i)||(i=u(t,i,n)),i}var o=f(t,e);if(o)return o;var s=Object.keys(e),y=a(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(e)),E(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(e);if(0===s.length){if(S(e)){var g=e.name?": "+e.name:"";return t.stylize("[Function"+g+"]","special")}if(O(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(A(e))return t.stylize(Date.prototype.toString.call(e),"date");if(E(e))return c(e)}var _="",m=!1,b=["{","}"];if(d(e)&&(m=!0,b=["[","]"]),S(e)){var w=e.name?": "+e.name:"";_=" [Function"+w+"]"}if(O(e)&&(_=" "+RegExp.prototype.toString.call(e)),A(e)&&(_=" "+Date.prototype.toUTCString.call(e)),E(e)&&(_=" "+c(e)),0===s.length&&(!m||0==e.length))return b[0]+_+b[1];if(0>n)return O(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);var B;return B=m?h(t,e,n,y,s):s.map(function(r){return p(t,e,n,y,r,m)}),t.seen.pop(),l(B,_,b)}function f(t,e){if(w(e))return t.stylize("undefined","undefined");if(v(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return m(e)?t.stylize(""+e,"number"):y(e)?t.stylize(""+e,"boolean"):g(e)?t.stylize("null","null"):void 0}function c(t){return"["+Error.prototype.toString.call(t)+"]"}function h(t,e,r,n,i){for(var o=[],s=0,a=e.length;a>s;++s)o.push(j(e,String(s))?p(t,e,r,n,String(s),!0):"");return i.forEach(function(i){i.match(/^\d+$/)||o.push(p(t,e,r,n,i,!0))}),o}function p(t,e,r,n,i,o){var s,a,f;if(f=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]},f.get?a=f.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):f.set&&(a=t.stylize("[Setter]","special")),j(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(f.value)<0?(a=g(r)?u(t,f.value,null):u(t,f.value,r-1),a.indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n"))):a=t.stylize("[Circular]","special")),w(s)){if(o&&i.match(/^\d+$/))return a;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function l(t,e,r){var n=0,i=t.reduce(function(t,e){return n++,e.indexOf("\n")>=0&&n++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function d(t){return Array.isArray(t)}function y(t){return"boolean"==typeof t}function g(t){return null===t}function _(t){return null==t}function m(t){return"number"==typeof t}function v(t){return"string"==typeof t}function b(t){return"symbol"==typeof t}function w(t){return void 0===t}function O(t){return B(t)&&"[object RegExp]"===T(t)}function B(t){return"object"==typeof t&&null!==t}function A(t){return B(t)&&"[object Date]"===T(t)}function E(t){return B(t)&&("[object Error]"===T(t)||t instanceof Error)}function S(t){return"function"==typeof t}function N(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function T(t){return Object.prototype.toString.call(t)}function $(t){return 10>t?"0"+t.toString(10):t.toString(10)}function x(){var t=new Date,e=[$(t.getHours()),$(t.getMinutes()),$(t.getSeconds())].join(":");return[t.getDate(),L[t.getMonth()],e].join(" ")}function j(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var D=/%[sdj%]/g;r.format=function(t){if(!v(t)){for(var e=[],r=0;r=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),a=n[r];o>r;a=n[++r])s+=g(a)||!B(a)?" "+a:" "+i(a);return s},r.deprecate=function(t,i){function o(){if(!s){if(e.throwDeprecation)throw new Error(i);e.traceDeprecation?console.trace(i):console.error(i),s=!0}return t.apply(this,arguments)}if(w(n.process))return function(){return r.deprecate(t,i).apply(this,arguments)};if(e.noDeprecation===!0)return t;var s=!1;return o};var I,M={};r.debuglog=function(t){if(w(I)&&(I=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!M[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var n=e.pid;M[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else M[t]=function(){};return M[t]},r.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=y,r.isNull=g,r.isNullOrUndefined=_,r.isNumber=m,r.isString=v,r.isSymbol=b,r.isUndefined=w,r.isRegExp=O,r.isObject=B,r.isDate=A,r.isError=E,r.isFunction=S,r.isPrimitive=N,r.isBuffer=t("./support/isBuffer");var L=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];r.log=function(){console.log("%s - %s",x(),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!B(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("FWaASH"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":47,FWaASH:46,inherits:45}],49:[function(t,e){function r(t,e){if(!(this instanceof r))return new r(t,e);if(this._bsontype="Binary",t instanceof Number?(this.sub_type=t,this.position=0):(this.sub_type=null==e?i:e,this.position=0),null==t||t instanceof Number)this.buffer="undefined"!=typeof n?new n(r.BUFFER_SIZE):"undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(r.BUFFER_SIZE)):new Array(r.BUFFER_SIZE),this.position=0;else{if("string"==typeof t)if("undefined"!=typeof n)this.buffer=new n(t);else{if("undefined"==typeof Uint8Array&&"[object Array]"!=Object.prototype.toString.call(t))throw new Error("only String, Buffer, Uint8Array or Array accepted");this.buffer=o(t)}else this.buffer=t;this.position=t.length}}if("undefined"==typeof window)var n=t("buffer").Buffer;r.prototype.put=function(t){if(null!=t.length&&"number"!=typeof t&&1!=t.length)throw new Error("only accepts single character String, Uint8Array or Array");if("number"!=typeof t&&0>t||t>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var e=null;if(e="string"==typeof t?t.charCodeAt(0):null!=t.length?t[0]:t,this.buffer.length>this.position)this.buffer[this.position++]=e;else if("undefined"!=typeof n&&n.isBuffer(this.buffer)){var i=new n(r.BUFFER_SIZE+this.buffer.length);this.buffer.copy(i,0,0,this.buffer.length),this.buffer=i,this.buffer[this.position++]=e}else{var i=null;i="[object Uint8Array]"==Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(r.BUFFER_SIZE+this.buffer.length)):new Array(r.BUFFER_SIZE+this.buffer.length);for(var o=0;othis.position?e+t.length:this.position;else if("undefined"!=typeof n&&"string"==typeof t&&n.isBuffer(this.buffer))this.buffer.write(t,"binary",e),this.position=e+t.length>this.position?e+t.length:this.position;else if("[object Uint8Array]"==Object.prototype.toString.call(t)||"[object Array]"==Object.prototype.toString.call(t)&&"string"!=typeof t){for(var i=0;ithis.position?e:this.position}else if("string"==typeof t){for(var i=0;ithis.position?e:this.position}},r.prototype.read=function(t,e){if(e=e&&e>0?e:this.position,this.buffer.slice)return this.buffer.slice(t,t+e);for(var r="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e)):new Array(e),n=0;e>n;n++)r[n]=this.buffer[t++];return r},r.prototype.value=function(t){if(t=null==t?!1:t,t&&"undefined"!=typeof n&&n.isBuffer(this.buffer)&&this.buffer.length==this.position)return this.buffer;if("undefined"!=typeof n&&n.isBuffer(this.buffer))return t?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position);if(t){if(null!=this.buffer.slice)return this.buffer.slice(0,this.position);for(var e="[object Uint8Array]"==Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(this.position)):new Array(this.position),r=0;ri;i++)n+=String.fromCharCode(t[i]);return n};r.BUFFER_SIZE=256,r.SUBTYPE_DEFAULT=0,r.SUBTYPE_FUNCTION=1,r.SUBTYPE_BYTE_ARRAY=2,r.SUBTYPE_UUID_OLD=3,r.SUBTYPE_UUID=4,r.SUBTYPE_MD5=5,r.SUBTYPE_USER_DEFINED=128,e.exports=r,e.exports.Binary=r},{buffer:40}],50:[function(t,e,n){(function(e){function i(t,e){return this instanceof i?(this.bigEndian=t,void(this.allowExceptions=e)):new i(t,e)}function o(t,e){this.bigEndian=t||0,this.buffer=[],this.setBuffer(e)}for(var s=String.fromCharCode,a=[],u=0;64>u;u++)a[u]=Math.pow(2,u);i.warn=function(t){if(this.allowExceptions)throw new Error(t);return 1},i.decodeFloat=function(t,e,r){var n=new this.Buffer(this.bigEndian,t);n.checkBuffer(e+r+1);var i=a[r-1]-1,o=n.readBits(e+r,1),s=n.readBits(e,r),u=0,f=2,c=n.buffer.length+(-e>>3)-1;do for(var h=n.buffer[++c],p=e%8||8,l=1<>=1;h&l&&(u+=1/f),f*=2);while(e-=p);return s==(i<<1)+1?u?0/0:o?-1/0:+1/0:(1+-2*o)*(s||u?s?Math.pow(2,s-i)*(1+u):Math.pow(2,-i+1)*u:0)},i.decodeInt=function(t,e,r,n){var i=new this.Buffer(this.bigEndian||n,t),o=i.readBits(0,e),s=a[e];return r&&o>=s/2?o-s:o},i.encodeFloat=function(t,e,n){var i,o,s,u,f,c=a[n-1]-1,h=-c+1,p=c,l=h-e,d=parseFloat(t),y=isNaN(d)||d==-1/0||d==+1/0?d:0,g=0,_=2*c+1+e+3,m=new Array(_),v=(d=0!==y?0:d)<0,b=Math.floor(d=Math.abs(d)),w=d-b;for(u=_;u;m[--u]=0);for(u=c+2;b&&u;m[--u]=b%2,b=Math.floor(b/2));for(u=c+1;w>0&&u;(m[++u]=((w*=2)>=1)-0)&&--w);for(u=-1;++u<_&&!m[u];);if(m[(i=e-1+(u=(g=c+1-u)>=h&&p>=g?u+1:c+1-(g=h-1)))+1]){if(!(o=m[i]))for(f=i+2;!o&&_>f;o=m[f++]);for(f=i+1;o&&--f>=0;(m[f]=!m[f]-0)&&(o=0));}for(u=0>u-2?-1:u-3;++u<_&&!m[u];);for((g=c+1-u)>=h&&p>=g?++u:h>g&&(g!=c+1-_&&l>g&&this.warn("encodeFloat::float underflow"),u=c+1-(g=h-1)),(b||0!==y)&&(this.warn(b?"encodeFloat::float overflow":"encodeFloat::"+y),g=p+1,u=c+2,y==-1/0?v=1:isNaN(y)&&(m[u]=1)),d=Math.abs(g+c),f=n+1,s="";--f;s=d%2+s,d=d>>=1);for(d=0,f=0,u=(s=(v?"1":"0")+s+m.slice(u,u+e).join("")).length,r=[];u;f=(f+1)%8)d+=(1<=i||-(i/2)>t)&&(this.warn("encodeInt::overflow"),t=0),0>t&&(t+=i);for(var o=[];t;o[o.length]=String.fromCharCode(t%256),t=Math.floor(t/256));for(e=-(-e>>3)-o.length;e--;o[o.length]="\x00");return(this.bigEndian||n?o.reverse():o).join("")},i.toSmall=function(t){return this.decodeInt(t,8,!0)},i.fromSmall=function(t){return this.encodeInt(t,8,!0)},i.toByte=function(t){return this.decodeInt(t,8,!1)},i.fromByte=function(t){return this.encodeInt(t,8,!1)},i.toShort=function(t){return this.decodeInt(t,16,!0)},i.fromShort=function(t){return this.encodeInt(t,16,!0)},i.toWord=function(t){return this.decodeInt(t,16,!1)},i.fromWord=function(t){return this.encodeInt(t,16,!1)},i.toInt=function(t){return this.decodeInt(t,32,!0)},i.fromInt=function(t){return this.encodeInt(t,32,!0)},i.toLong=function(t){return this.decodeInt(t,64,!0)},i.fromLong=function(t){return this.encodeInt(t,64,!0)},i.toDWord=function(t){return this.decodeInt(t,32,!1)},i.fromDWord=function(t){return this.encodeInt(t,32,!1)},i.toQWord=function(t){return this.decodeInt(t,64,!0)},i.fromQWord=function(t){return this.encodeInt(t,64,!0)},i.toFloat=function(t){return this.decodeFloat(t,23,8)},i.fromFloat=function(t){return this.encodeFloat(t,23,8)},i.toDouble=function(t){return this.decodeFloat(t,52,11)},i.fromDouble=function(t){return this.encodeFloat(t,52,11)},i.encode_int32=function(t,e){var r,n,i,o,a;return a=0>t?t+4294967296:t,r=Math.floor(a/16777215),a&=16777215,n=Math.floor(a/65535),a&=65535,i=Math.floor(a/255),a&=255,o=Math.floor(a),e?[s(r),s(n),s(i),s(o)]:s(r)+s(n)+s(i)+s(o)},i.encode_int64=function(t){var e,r,n,i,o,a,u,f,c;return c=0>t?t+0x10000000000000000:t,e=Math.floor(c/72057594037927940),c&=72057594037927940,r=Math.floor(c/0xffffffffffff),c&=0xffffffffffff,n=Math.floor(c/0xffffffffff),c&=0xffffffffff,i=Math.floor(c/4294967295),c&=4294967295,o=Math.floor(c/16777215),c&=16777215,a=Math.floor(c/65535),c&=65535,u=Math.floor(c/255),c&=255,f=Math.floor(c),s(e)+s(r)+s(n)+s(i)+s(o)+s(a)+s(u)+s(f)},i.decode_utf8=function(t){for(var e,r=t.length,n="",i=0,o=0,s=0;r>i;)o=t.charCodeAt(i),128>o?(n+=String.fromCharCode(o),i++):o>191&&224>o?(s=t.charCodeAt(i+1),n+=String.fromCharCode((31&o)<<6|63&s),i+=2):(s=t.charCodeAt(i+1),e=t.charCodeAt(i+2),n+=String.fromCharCode((15&o)<<12|(63&s)<<6|63&e),i+=3);return n},i.encode_cstring=function(t){return unescape(encodeURIComponent(t))+i.fromByte(0)},i.encode_utf8=function(t){for(var e,r="",n=0,i=t.length;i>n;n++)e=t.charCodeAt(n),128>e?r+=String.fromCharCode(e):e>127&&2048>e?(r+=String.fromCharCode(e>>6|192),r+=String.fromCharCode(63&e|128)):(r+=String.fromCharCode(e>>12|224),r+=String.fromCharCode(e>>6&63|128),r+=String.fromCharCode(63&e|128));return r},i.hprint=function(t){for(var r,n=0,i=t.length;i>n;n++)t.charCodeAt(n)<32?(r=t.charCodeAt(n)<=15?"0"+t.charCodeAt(n).toString(16):t.charCodeAt(n).toString(16),e.stdout.write(r+" ")):(r=t.charCodeAt(n)<=15?"0"+t.charCodeAt(n).toString(16):t.charCodeAt(n).toString(16),e.stdout.write(r+" "));e.stdout.write("\n\n")},i.ilprint=function(e){for(var r,n=0,i=e.length;i>n;n++)e.charCodeAt(n)<32?(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(10):e.charCodeAt(n).toString(10),t("util").debug(r+" : ")):(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(10):e.charCodeAt(n).toString(10),t("util").debug(r+" : "+e.charAt(n)))},i.hlprint=function(e){for(var r,n=0,i=e.length;i>n;n++)e.charCodeAt(n)<32?(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(16):e.charCodeAt(n).toString(16),t("util").debug(r+" : ")):(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(16):e.charCodeAt(n).toString(16),t("util").debug(r+" : "+e.charAt(n)))},o.prototype.setBuffer=function(t){var e,r,n;if(t){for(r=e=t.length,n=this.buffer=new Array(e);r;n[e-r]=t.charCodeAt(--r));this.bigEndian&&n.reverse()}},o.prototype.hasNeededBits=function(t){return this.buffer.length>=-(-t>>3)},o.prototype.checkBuffer=function(t){if(!this.hasNeededBits(t))throw new Error("checkBuffer::missing bytes")},o.prototype.readBits=function(t,e){function r(t,e){for(;e--;t=1073741824==(1073741824&(t%=2147483648))?2*t:2*(t-1073741824)+2147483647+1);return t}if(0>t||0>=e)return 0;this.checkBuffer(t+e);for(var n,i=t%8,o=this.buffer.length-(t>>3)-1,s=this.buffer.length+(-(t+e)>>3),a=o-s,u=(this.buffer[o]>>i&(1<<(a?8-i:e))-1)+(a&&(n=(t+e)%8)?(this.buffer[s++]&(1<=BSON.JS_INT_MIN&&e<=BSON.JS_INT_MAX&&e>=BSON.BSON_INT32_MIN&&e<=BSON.BSON_INT32_MAX?(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+5:(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+9;case"undefined":return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1;case"boolean":return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+2;case"object":if(null==e||e instanceof MinKey||e instanceof MaxKey||"MinKey"==e._bsontype||"MaxKey"==e._bsontype)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1;if(e instanceof ObjectID||"ObjectID"==e._bsontype)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+13;if(e instanceof Date||isDate(e))return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+9;if("undefined"!=typeof Buffer&&Buffer.isBuffer(e))return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+6+e.length;if(e instanceof Long||e instanceof Double||e instanceof Timestamp||"Long"==e._bsontype||"Double"==e._bsontype||"Timestamp"==e._bsontype)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+9;if(e instanceof Code||"Code"==e._bsontype)return null!=e.scope&&Object.keys(e.scope).length>0?(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+4+4+(n?Buffer.byteLength(e.code.toString(),"utf8"):numberOfBytes(e.code.toString()))+1+BSON.calculateObjectSize(e.scope,r):(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+4+(n?Buffer.byteLength(e.code.toString(),"utf8"):numberOfBytes(e.code.toString()))+1;if(e instanceof Binary||"Binary"==e._bsontype)return e.sub_type==Binary.SUBTYPE_BYTE_ARRAY?(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+(e.position+1+4+1+4):(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+(e.position+1+4+1);if(e instanceof Symbol||"Symbol"==e._bsontype)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+((n?Buffer.byteLength(e.value,"utf8"):numberOfBytes(e.value))+4+1+1);if(e instanceof DBRef||"DBRef"==e._bsontype){var i={$ref:e.namespace,$id:e.oid};return null!=e.db&&(i.$db=e.db),(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+BSON.calculateObjectSize(i,r)}return e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)?(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+(n?Buffer.byteLength(e.source,"utf8"):numberOfBytes(e.source))+1+(e.global?1:0)+(e.ignoreCase?1:0)+(e.multiline?1:0)+1:(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+BSON.calculateObjectSize(e,r)+1;case"function":if(e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)||"[object RegExp]"==String.call(e))return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+(n?Buffer.byteLength(e.source,"utf8"):numberOfBytes(e.source))+1+(e.global?1:0)+(e.ignoreCase?1:0)+(e.multiline?1:0)+1;if(r&&null!=e.scope&&Object.keys(e.scope).length>0)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+4+4+(n?Buffer.byteLength(e.toString(),"utf8"):numberOfBytes(e.toString()))+1+BSON.calculateObjectSize(e.scope,r);if(r)return(null!=t?(n?Buffer.byteLength(t,"utf8"):numberOfBytes(t))+1:0)+1+4+(n?Buffer.byteLength(e.toString(),"utf8"):numberOfBytes(e.toString()))+1}return 0}var Long=require("./long").Long,Double=require("./double").Double,Timestamp=require("./timestamp").Timestamp,ObjectID=require("./objectid").ObjectID,Symbol=require("./symbol").Symbol,Code=require("./code").Code,MinKey=require("./min_key").MinKey,MaxKey=require("./max_key").MaxKey,DBRef=require("./db_ref").DBRef,Binary=require("./binary").Binary,BinaryParser=require("./binary_parser").BinaryParser,writeIEEE754=require("./float_parser").writeIEEE754,readIEEE754=require("./float_parser").readIEEE754,isDate=function(t){return"object"==typeof t&&"[object Date]"===Object.prototype.toString.call(t)};BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.calculateObjectSize=function(t,e){var r=5;if(Array.isArray(t))for(var n=0;n>8&255,r[n++]=o>>16&255,r[n++]=o>>24&255,serializeObject(t,e,r,n,i)-1};var serializeObject=function(t,e,r,n,i){if(t.toBSON){if("function"!=typeof t.toBSON)throw new Error("toBSON is not a function");if(t=t.toBSON(),null!=t&&"object"!=typeof t)throw new Error("toBSON function did not return an object")}if(Array.isArray(t))for(var o=0;o>=8;while(e);n=n.concat(r.reverse())}return n},numberOfBytes=function(t){for(var e,r,n=0,i=0;i>=8;while(e);n+=r.length}return n},writeToTypedArray=function(t,e,r){for(var n=stringToBytes(e),i=0;i>24&255,n[i+2]=a>>16&255,n[i+1]=a>>8&255,n[i]=255&a,i+=4,supportsBuffer?n.write(e,i,"utf8"):writeToTypedArray(n,e,i),i=i+a-1,n[i++]=0,i;case"number":if(Math.floor(e)===e&&e>=BSON.JS_INT_MIN&&e<=BSON.JS_INT_MAX)if(e>=BSON.BSON_INT32_MIN&&e<=BSON.BSON_INT32_MAX){n[i++]=BSON.BSON_DATA_INT;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0,n[i++]=255&e,n[i++]=e>>8&255,n[i++]=e>>16&255,n[i++]=e>>24&255}else if(e>=BSON.JS_INT_MIN&&e<=BSON.JS_INT_MAX){n[i++]=BSON.BSON_DATA_NUMBER;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0,writeIEEE754(n,e,i,"little",52,8),i+=8}else{n[i++]=BSON.BSON_DATA_LONG;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var u=Long.fromNumber(e),f=u.getLowBits(),c=u.getHighBits();n[i++]=255&f,n[i++]=f>>8&255,n[i++]=f>>16&255,n[i++]=f>>24&255,n[i++]=255&c,n[i++]=c>>8&255,n[i++]=c>>16&255,n[i++]=c>>24&255}else{n[i++]=BSON.BSON_DATA_NUMBER;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0,writeIEEE754(n,e,i,"little",52,8),i+=8}return i;case"undefined":n[i++]=BSON.BSON_DATA_NULL;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,i;case"boolean":n[i++]=BSON.BSON_DATA_BOOLEAN;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,n[i++]=e?1:0,i;case"object":if(null===e||e instanceof MinKey||e instanceof MaxKey||"MinKey"==e._bsontype||"MaxKey"==e._bsontype){n[i++]=null===e?BSON.BSON_DATA_NULL:e instanceof MinKey?BSON.BSON_DATA_MIN_KEY:BSON.BSON_DATA_MAX_KEY;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,i}if(e instanceof ObjectID||"ObjectID"==e._bsontype){n[i++]=BSON.BSON_DATA_OID;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,supportsBuffer?n.write(e.id,i,"binary"):writeToTypedArray(n,e.id,i),i+=12}if(e instanceof Date||isDate(e)){n[i++]=BSON.BSON_DATA_DATE;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var h=Long.fromNumber(e.getTime()),f=h.getLowBits(),c=h.getHighBits();return n[i++]=255&f,n[i++]=f>>8&255,n[i++]=f>>16&255,n[i++]=f>>24&255,n[i++]=255&c,n[i++]=c>>8&255,n[i++]=c>>16&255,n[i++]=c>>24&255,i}if("undefined"!=typeof Buffer&&Buffer.isBuffer(e)){n[i++]=BSON.BSON_DATA_BINARY;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var a=e.length;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,n[i++]=BSON.BSON_BINARY_SUBTYPE_DEFAULT,e.copy(n,i,0,a),i+=a}if(e instanceof Long||e instanceof Timestamp||"Long"==e._bsontype||"Timestamp"==e._bsontype){n[i++]=e instanceof Long||"Long"==e._bsontype?BSON.BSON_DATA_LONG:BSON.BSON_DATA_TIMESTAMP;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var f=e.getLowBits(),c=e.getHighBits();return n[i++]=255&f,n[i++]=f>>8&255,n[i++]=f>>16&255,n[i++]=f>>24&255,n[i++]=255&c,n[i++]=c>>8&255,n[i++]=c>>16&255,n[i++]=c>>24&255,i}if(e instanceof Double||"Double"==e._bsontype){n[i++]=BSON.BSON_DATA_NUMBER;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,writeIEEE754(n,e,i,"little",52,8),i+=8}if(e instanceof Code||"Code"==e._bsontype){if(null!=e.scope&&Object.keys(e.scope).length>0){n[i++]=BSON.BSON_DATA_CODE_W_SCOPE;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var p=BSON.calculateObjectSize(e.scope,o),l=e.code.toString(),d=supportsBuffer?Buffer.byteLength(l)+1:numberOfBytes(l)+1,y=4+d+p+4;n[i++]=255&y,n[i++]=y>>8&255,n[i++]=y>>16&255,n[i++]=y>>24&255,n[i++]=255&d,n[i++]=d>>8&255,n[i++]=d>>16&255,n[i++]=d>>24&255,supportsBuffer?n.write(l,i,"utf8"):writeToTypedArray(n,l,i),i=i+d-1,n[i++]=0;var g=supportsBuffer?new Buffer(p):new Uint8Array(new ArrayBuffer(p));serializeObject(e.scope,r,g,0,o); -var _=p;return n[i++]=255&_,n[i++]=_>>8&255,n[i++]=_>>16&255,n[i++]=_>>24&255,supportsBuffer?g.copy(n,i,0,p):n.set(g,i),i=i+_-5,n[i++]=0,i}n[i++]=BSON.BSON_DATA_CODE;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var l=e.code.toString(),a=supportsBuffer?Buffer.byteLength(l)+1:numberOfBytes(l)+1;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,supportsBuffer?n.write(l,i,"utf8"):writeToTypedArray(n,l,i),i=i+a-1,n[i++]=0,i}if(e instanceof Binary||"Binary"==e._bsontype){n[i++]=BSON.BSON_DATA_BINARY;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var m=e.value(!0),a=e.position;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,n[i++]=e.sub_type,e.sub_type==Binary.SUBTYPE_BYTE_ARRAY&&(n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255),supportsBuffer?m.copy(n,i,0,e.position):n.set(m,i),i+=e.position}if(e instanceof Symbol||"Symbol"==e._bsontype){n[i++]=BSON.BSON_DATA_SYMBOL;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var a=supportsBuffer?Buffer.byteLength(e.value)+1:numberOfBytes(e.value)+1;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,n.write(e.value,i,"utf8"),i=i+a-1,n[i++]=0,i}if(e instanceof DBRef||"DBRef"==e._bsontype){n[i++]=BSON.BSON_DATA_OBJECT;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var v={$ref:e.namespace,$id:e.oid};null!=e.db&&(v.$db=e.db);var a=BSON.calculateObjectSize(v,o),b=BSON.serializeWithBufferAndIndex(v,r,n,i,o);return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,n[b++]=0,b}if(e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)){n[i++]=BSON.BSON_DATA_REGEXP;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,supportsBuffer?n.write(e.source,i,"utf8"):writeToTypedArray(n,e.source,i),i+=supportsBuffer?Buffer.byteLength(e.source):numberOfBytes(e.source),n[i++]=0,e.global&&(n[i++]=115),e.ignoreCase&&(n[i++]=105),e.multiline&&(n[i++]=109),n[i++]=0,i}n[i++]=Array.isArray(e)?BSON.BSON_DATA_ARRAY:BSON.BSON_DATA_OBJECT;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var b=serializeObject(e,r,n,i+4,o),a=b-i;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,b;case"function":if(e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)||"[object RegExp]"==String.call(e)){n[i++]=BSON.BSON_DATA_REGEXP;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);return i=i+s+1,n[i-1]=0,n.write(e.source,i,"utf8"),i+=supportsBuffer?Buffer.byteLength(e.source):numberOfBytes(e.source),n[i++]=0,e.global&&(n[i++]=115),e.ignoreCase&&(n[i++]=105),e.multiline&&(n[i++]=109),n[i++]=0,i}if(o&&null!=e.scope&&Object.keys(e.scope).length>0){n[i++]=BSON.BSON_DATA_CODE_W_SCOPE;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var p=BSON.calculateObjectSize(e.scope,o),l=e.toString(),d=supportsBuffer?Buffer.byteLength(l)+1:numberOfBytes(l)+1,y=4+d+p;n[i++]=255&y,n[i++]=y>>8&255,n[i++]=y>>16&255,n[i++]=y>>24&255,n[i++]=255&d,n[i++]=d>>8&255,n[i++]=d>>16&255,n[i++]=d>>24&255,supportsBuffer?n.write(l,i,"utf8"):writeToTypedArray(n,l,i),i=i+d-1,n[i++]=0;var g=new Buffer(p);serializeObject(e.scope,r,g,0,o);var _=p-4;return n[i++]=255&_,n[i++]=_>>8&255,n[i++]=_>>16&255,n[i++]=_>>24&255,g.copy(n,i,0,p),i=i+_-5,n[i++]=0,i}if(o){n[i++]=BSON.BSON_DATA_CODE;var s=supportsBuffer?n.write(t,i,"utf8"):writeToTypedArray(n,t,i);i=i+s+1,n[i-1]=0;var l=e.toString(),a=supportsBuffer?Buffer.byteLength(l)+1:numberOfBytes(l)+1;return n[i++]=255&a,n[i++]=a>>8&255,n[i++]=a>>16&255,n[i++]=a>>24&255,supportsBuffer?n.write(l,i,"utf8"):writeToTypedArray(n,l,i),i=i+a-1,n[i++]=0,i}}return i};BSON.serialize=function(t,e,r,n){if(null==t||"object"!=typeof t||Array.isArray(t))throw new Error("Only javascript objects supported");var i=null,o=BSON.calculateObjectSize(t,n);return(i="undefined"!=typeof Buffer)?(i=new Buffer(o),r=!0):i="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(o)):new Array(o),BSON.serializeWithBufferAndIndex(t,e,i,0,n),i};var functionCache=BSON.functionCache={},table=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],crc32=function(t,e,r){var n=0,i=0,o=0;n=-1^n;for(var s=e,a=r;a>s;s++)o=255&(n^t[s]),i=table[o],n=n>>>8^i;return-1^n};BSON.deserializeStream=function(t,e,r,n,i,o){o=null!=o?o:{};for(var s=e,a=0;r>a;a++){var u=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;o.index=s,n[i+a]=BSON.deserialize(t,o),s+=u}return s};var isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},convertUint8ArrayToUtf8String=function(t,e,r){return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(t,e,r))},convertArraytoUtf8BinaryString=function(t,e,r){for(var n="",i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n};BSON.deserialize=function(t,e,r){e=null==e?{}:e;var n=null==e.evalFunctions?!1:e.evalFunctions,i=null==e.cacheFunctions?!1:e.cacheFunctions,o=null==e.cacheFunctionsCrc32?!1:e.cacheFunctionsCrc32,s=null==e.promoteLongs?!0:e.promoteLongs;if(t.length<5)throw new Error("corrupt bson message < 5 bytes long");var a="number"==typeof e.index?e.index:0,u=function(){for(var e=a;0!==t[e]&&e=t.length)throw new Error("Bad BSON Document: illegal CString");var r=supportsBuffer&&Buffer.isBuffer(t)?t.toString("utf8",a,e):convertUint8ArrayToUtf8String(t,a,e);return a=e+1,r},f=r?[]:{},c=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24;if(5>c||c>t.length)throw new Error("corrupt bson message");for(;;){var h=t[a++];if(0==h)break;var p=u();switch(h){case BSON.BSON_DATA_OID:var l=supportsBuffer&&Buffer.isBuffer(t)?t.toString("binary",a,a+12):convertArraytoUtf8BinaryString(t,a,a+12);f[p]=new ObjectID(l),a+=12;break;case BSON.BSON_DATA_STRING:var d=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24;f[p]=supportsBuffer&&Buffer.isBuffer(t)?t.toString("utf8",a,a+d-1):convertUint8ArrayToUtf8String(t,a,a+d-1),a+=d;break;case BSON.BSON_DATA_INT:f[p]=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24;break;case BSON.BSON_DATA_NUMBER:f[p]=readIEEE754(t,a,"little",52,8),a+=8;break;case BSON.BSON_DATA_DATE:var y=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24,g=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24;f[p]=new Date(new Long(y,g).toNumber());break;case BSON.BSON_DATA_BOOLEAN:f[p]=1==t[a++];break;case BSON.BSON_DATA_UNDEFINED:case BSON.BSON_DATA_NULL:f[p]=null;break;case BSON.BSON_DATA_BINARY:var _=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24,m=t[a++];if(null!=t.slice)m==Binary.SUBTYPE_BYTE_ARRAY&&(_=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24),f[p]=new Binary(t.slice(a,a+_),m);else{var v="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(_)):new Array(_);m==Binary.SUBTYPE_BYTE_ARRAY&&(_=t[a++]|t[a++]<<8|t[a++]<<16|t[a++]<<24);for(var b=0;_>b;b++)v[b]=t[a+b];f[p]=new Binary(v,m)}a+=_;break;case BSON.BSON_DATA_ARRAY:e.index=a;var w=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24;f[p]=BSON.deserialize(t,e,!0),a+=w;break;case BSON.BSON_DATA_OBJECT:e.index=a;var w=t[a]|t[a+1]<<8|t[a+2]<<16|t[a+3]<<24;f[p]=BSON.deserialize(t,e,!1),a+=w;break;case BSON.BSON_DATA_REGEXP:for(var O=u(),B=u(),A=new Array(B.length),b=0;b>1,h=-7,p=a?0:i-1,l=a?1:-1,d=t[e+p];for(p+=l,o=d&(1<<-h)-1,d>>=-h,h+=u;h>0;o=256*o+t[e+p],p+=l,h-=8);for(s=o&(1<<-h)-1,o>>=-h,h+=n;h>0;s=256*s+t[e+p],p+=l,h-=8);if(0===o)o=1-c;else{if(o===f)return s?0/0:1/0*(d?-1:1);s+=Math.pow(2,n),o-=c}return(d?-1:1)*s*Math.pow(2,o-n)},i=function(t,e,r,n,i,o){var s,a,u,f="big"===n,c=8*o-i-1,h=(1<>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=f?o-1:0,y=f?-1:1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||1/0===e?(a=isNaN(e)?1:0,s=h):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),e+=s+p>=1?l/u:l*Math.pow(2,1-p),e*u>=2&&(s++,u/=2),s+p>=h?(a=0,s=h):s+p>=1?(a=(e*u-1)*Math.pow(2,i),s+=p):(a=e*Math.pow(2,p-1)*Math.pow(2,i),s=0));i>=8;t[r+d]=255&a,d+=y,a/=256,i-=8);for(s=s<0;t[r+d]=255&s,d+=y,s/=256,c-=8);t[r+d-y]|=128*g};r.readIEEE754=n,r.writeIEEE754=i},{}],56:[function(t,e){function r(t,e){return this instanceof r?(this._bsontype="Long",this.low_=0|t,void(this.high_=0|e)):new r(t,e)}r.prototype.toInt=function(){return this.low_},r.prototype.toNumber=function(){return this.high_*r.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},r.prototype.toJSON=function(){return this.toString()},r.prototype.toString=function(t){var e=t||10;if(2>e||e>36)throw Error("radix out of range: "+e);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(r.MIN_VALUE)){var n=r.fromNumber(e),i=this.div(n),o=i.multiply(n).subtract(this);return i.toString(e)+o.toInt().toString(e)}return"-"+this.negate().toString(e)}for(var s=r.fromNumber(Math.pow(e,6)),o=this,a="";;){var u=o.div(s),f=o.subtract(u.multiply(s)).toInt(),c=f.toString(e);if(o=u,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}},r.prototype.getHighBits=function(){return this.high_},r.prototype.getLowBits=function(){return this.low_},r.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:r.TWO_PWR_32_DBL_+this.low_},r.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(r.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!=this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},r.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},r.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},r.prototype.negate=function(){return this.equals(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)},r.prototype.add=function(t){var e=this.high_>>>16,n=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,f=65535&t.low_,c=0,h=0,p=0,l=0;return l+=o+f,p+=l>>>16,l&=65535,p+=i+u,h+=p>>>16,p&=65535,h+=n+a,c+=h>>>16,h&=65535,c+=e+s,c&=65535,r.fromBits(p<<16|l,c<<16|h)},r.prototype.subtract=function(t){return this.add(t.negate())},r.prototype.multiply=function(t){if(this.isZero())return r.ZERO;if(t.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.equals(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(r.TWO_PWR_24_)&&t.lessThan(r.TWO_PWR_24_))return r.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,n=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,f=65535&t.low_,c=0,h=0,p=0,l=0;return l+=o*f,p+=l>>>16,l&=65535,p+=i*f,h+=p>>>16,p&=65535,p+=o*u,h+=p>>>16,p&=65535,h+=n*f,c+=h>>>16,h&=65535,h+=i*u,c+=h>>>16,h&=65535,h+=o*a,c+=h>>>16,h&=65535,c+=e*f+n*u+i*a+o*s,c&=65535,r.fromBits(p<<16|l,c<<16|h)},r.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE)){if(t.equals(r.ONE)||t.equals(r.NEG_ONE))return r.MIN_VALUE;if(t.equals(r.MIN_VALUE))return r.ONE;var e=this.shiftRight(1),n=e.div(t).shiftLeft(1);if(n.equals(r.ZERO))return t.isNegative()?r.ONE:r.NEG_ONE;var i=this.subtract(t.multiply(n)),o=n.add(i.div(t));return o}if(t.equals(r.MIN_VALUE))return r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();for(var s=r.ZERO,i=this;i.greaterThanOrEqual(t);){for(var n=Math.max(1,Math.floor(i.toNumber()/t.toNumber())),a=Math.ceil(Math.log(n)/Math.LN2),u=48>=a?1:Math.pow(2,a-48),f=r.fromNumber(n),c=f.multiply(t);c.isNegative()||c.greaterThan(i);)n-=u,f=r.fromNumber(n),c=f.multiply(t);f.isZero()&&(f=r.ONE),s=s.add(f),i=i.subtract(c)}return s},r.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},r.prototype.not=function(){return r.fromBits(~this.low_,~this.high_)},r.prototype.and=function(t){return r.fromBits(this.low_&t.low_,this.high_&t.high_)},r.prototype.or=function(t){return r.fromBits(this.low_|t.low_,this.high_|t.high_)},r.prototype.xor=function(t){return r.fromBits(this.low_^t.low_,this.high_^t.high_)},r.prototype.shiftLeft=function(t){if(t&=63,0==t)return this;var e=this.low_;if(32>t){var n=this.high_;return r.fromBits(e<>>32-t)}return r.fromBits(0,e<t){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>t)}return r.fromBits(e>>t-32,e>=0?0:-1)},r.prototype.shiftRightUnsigned=function(t){if(t&=63,0==t)return this;var e=this.high_;if(32>t){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>>t)}return 32==t?r.fromBits(e,0):r.fromBits(e>>>t-32,0)},r.fromInt=function(t){if(t>=-128&&128>t){var e=r.INT_CACHE_[t];if(e)return e}var n=new r(0|t,0>t?-1:0);return t>=-128&&128>t&&(r.INT_CACHE_[t]=n),n},r.fromNumber=function(t){return isNaN(t)||!isFinite(t)?r.ZERO:t<=-r.TWO_PWR_63_DBL_?r.MIN_VALUE:t+1>=r.TWO_PWR_63_DBL_?r.MAX_VALUE:0>t?r.fromNumber(-t).negate():new r(t%r.TWO_PWR_32_DBL_|0,t/r.TWO_PWR_32_DBL_|0)},r.fromBits=function(t,e){return new r(t,e)},r.fromString=function(t,e){if(0==t.length)throw Error("number format error: empty string");var n=e||10;if(2>n||n>36)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return r.fromString(t.substring(1),n).negate();if(t.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+t);for(var i=r.fromNumber(Math.pow(n,8)),o=r.ZERO,s=0;sa){var f=r.fromNumber(Math.pow(n,a));o=o.multiply(f).add(r.fromNumber(u))}else o=o.multiply(i),o=o.add(r.fromNumber(u))}return o},r.INT_CACHE_={},r.TWO_PWR_16_DBL_=65536,r.TWO_PWR_24_DBL_=1<<24,r.TWO_PWR_32_DBL_=r.TWO_PWR_16_DBL_*r.TWO_PWR_16_DBL_,r.TWO_PWR_31_DBL_=r.TWO_PWR_32_DBL_/2,r.TWO_PWR_48_DBL_=r.TWO_PWR_32_DBL_*r.TWO_PWR_16_DBL_,r.TWO_PWR_64_DBL_=r.TWO_PWR_32_DBL_*r.TWO_PWR_32_DBL_,r.TWO_PWR_63_DBL_=r.TWO_PWR_64_DBL_/2,r.ZERO=r.fromInt(0),r.ONE=r.fromInt(1),r.NEG_ONE=r.fromInt(-1),r.MAX_VALUE=r.fromBits(-1,2147483647),r.MIN_VALUE=r.fromBits(0,-2147483648),r.TWO_PWR_24_=r.fromInt(1<<24),e.exports=r,e.exports.Long=r},{}],57:[function(t,e){function r(){return this instanceof r?void(this._bsontype="MaxKey"):new r}e.exports=r,e.exports.MaxKey=r},{}],58:[function(t,e){function r(){return this instanceof r?void(this._bsontype="MinKey"):new r}e.exports=r,e.exports.MinKey=r},{}],59:[function(t,e){(function(r){for(var n=t("./binary_parser").BinaryParser,i=parseInt(16777215*Math.random(),10),o=new RegExp("^[0-9a-fA-F]{24}$"),s=function t(e){if(!(this instanceof t))return new t(e);if(e instanceof t)return e;this._bsontype="ObjectID";var r=t.isValid(e);if(!r&&null!=e)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");return r&&"string"==typeof e&&24==e.length?t.createFromHexString(e):(null==e||"number"==typeof e?this.id=this.generate(e):null!=e&&12===e.length&&(this.id=e),void(t.cacheHexString&&(this.__id=this.toHexString())))},a=[],u=0;256>u;u++)a[u]=(15>=u?"0":"")+u.toString(16);s.prototype.toHexString=function(){if(s.cacheHexString&&this.__id)return this.__id;for(var t="",e=0;e24)throw new Error("Id cannot be longer than 12 bytes");for(var r,i,o="",a=0;e>a;a+=2)r=t.substr(a,2),i=parseInt(r,16),o+=n.fromByte(i);return new s(o,t)},s.isValid=function(t){return null==t?!1:null!=t&&"number"!=typeof t&&12!=t.length&&24!=t.length?!1:"string"==typeof t&&24==t.length?o.test(t):!0},Object.defineProperty(s.prototype,"generationTime",{enumerable:!0,get:function(){return Math.floor(n.decodeInt(this.id.substring(0,4),32,!0,!0))},set:function(t){var t=n.encodeInt(t,32,!0,!0);this.id=t+this.id.substr(4),this.toHexString()}}),e.exports=s,e.exports.ObjectID=s,e.exports.ObjectId=s}).call(this,t("FWaASH"))},{"./binary_parser":50,FWaASH:46}],60:[function(t,e){function r(t){return this instanceof r?(this._bsontype="Symbol",void(this.value=t)):new r(t)}r.prototype.valueOf=function(){return this.value},r.prototype.toString=function(){return this.value},r.prototype.inspect=function(){return this.value},r.prototype.toJSON=function(){return this.value},e.exports=r,e.exports.Symbol=r},{}],61:[function(t,e){function r(t,e){return this instanceof r?(this._bsontype="Timestamp",this.low_=0|t,void(this.high_=0|e)):new r(t,e)}r.prototype.toInt=function(){return this.low_},r.prototype.toNumber=function(){return this.high_*r.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},r.prototype.toJSON=function(){return this.toString()},r.prototype.toString=function(t){var e=t||10;if(2>e||e>36)throw Error("radix out of range: "+e);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(r.MIN_VALUE)){var n=r.fromNumber(e),i=this.div(n),o=i.multiply(n).subtract(this);return i.toString(e)+o.toInt().toString(e)}return"-"+this.negate().toString(e)}for(var s=r.fromNumber(Math.pow(e,6)),o=this,a="";;){var u=o.div(s),f=o.subtract(u.multiply(s)).toInt(),c=f.toString(e);if(o=u,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}},r.prototype.getHighBits=function(){return this.high_},r.prototype.getLowBits=function(){return this.low_},r.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:r.TWO_PWR_32_DBL_+this.low_},r.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(r.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!=this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},r.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},r.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},r.prototype.negate=function(){return this.equals(r.MIN_VALUE)?r.MIN_VALUE:this.not().add(r.ONE)},r.prototype.add=function(t){var e=this.high_>>>16,n=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,f=65535&t.low_,c=0,h=0,p=0,l=0;return l+=o+f,p+=l>>>16,l&=65535,p+=i+u,h+=p>>>16,p&=65535,h+=n+a,c+=h>>>16,h&=65535,c+=e+s,c&=65535,r.fromBits(p<<16|l,c<<16|h)},r.prototype.subtract=function(t){return this.add(t.negate())},r.prototype.multiply=function(t){if(this.isZero())return r.ZERO;if(t.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE))return t.isOdd()?r.MIN_VALUE:r.ZERO;if(t.equals(r.MIN_VALUE))return this.isOdd()?r.MIN_VALUE:r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(r.TWO_PWR_24_)&&t.lessThan(r.TWO_PWR_24_))return r.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,n=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,f=65535&t.low_,c=0,h=0,p=0,l=0;return l+=o*f,p+=l>>>16,l&=65535,p+=i*f,h+=p>>>16,p&=65535,p+=o*u,h+=p>>>16,p&=65535,h+=n*f,c+=h>>>16,h&=65535,h+=i*u,c+=h>>>16,h&=65535,h+=o*a,c+=h>>>16,h&=65535,c+=e*f+n*u+i*a+o*s,c&=65535,r.fromBits(p<<16|l,c<<16|h)},r.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return r.ZERO;if(this.equals(r.MIN_VALUE)){if(t.equals(r.ONE)||t.equals(r.NEG_ONE))return r.MIN_VALUE;if(t.equals(r.MIN_VALUE))return r.ONE;var e=this.shiftRight(1),n=e.div(t).shiftLeft(1);if(n.equals(r.ZERO))return t.isNegative()?r.ONE:r.NEG_ONE;var i=this.subtract(t.multiply(n)),o=n.add(i.div(t));return o}if(t.equals(r.MIN_VALUE))return r.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();for(var s=r.ZERO,i=this;i.greaterThanOrEqual(t);){for(var n=Math.max(1,Math.floor(i.toNumber()/t.toNumber())),a=Math.ceil(Math.log(n)/Math.LN2),u=48>=a?1:Math.pow(2,a-48),f=r.fromNumber(n),c=f.multiply(t);c.isNegative()||c.greaterThan(i);)n-=u,f=r.fromNumber(n),c=f.multiply(t);f.isZero()&&(f=r.ONE),s=s.add(f),i=i.subtract(c)}return s},r.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},r.prototype.not=function(){return r.fromBits(~this.low_,~this.high_)},r.prototype.and=function(t){return r.fromBits(this.low_&t.low_,this.high_&t.high_)},r.prototype.or=function(t){return r.fromBits(this.low_|t.low_,this.high_|t.high_)},r.prototype.xor=function(t){return r.fromBits(this.low_^t.low_,this.high_^t.high_)},r.prototype.shiftLeft=function(t){if(t&=63,0==t)return this;var e=this.low_;if(32>t){var n=this.high_;return r.fromBits(e<>>32-t)}return r.fromBits(0,e<t){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>t)}return r.fromBits(e>>t-32,e>=0?0:-1)},r.prototype.shiftRightUnsigned=function(t){if(t&=63,0==t)return this;var e=this.high_;if(32>t){var n=this.low_;return r.fromBits(n>>>t|e<<32-t,e>>>t)}return 32==t?r.fromBits(e,0):r.fromBits(e>>>t-32,0)},r.fromInt=function(t){if(t>=-128&&128>t){var e=r.INT_CACHE_[t];if(e)return e}var n=new r(0|t,0>t?-1:0);return t>=-128&&128>t&&(r.INT_CACHE_[t]=n),n},r.fromNumber=function(t){return isNaN(t)||!isFinite(t)?r.ZERO:t<=-r.TWO_PWR_63_DBL_?r.MIN_VALUE:t+1>=r.TWO_PWR_63_DBL_?r.MAX_VALUE:0>t?r.fromNumber(-t).negate():new r(t%r.TWO_PWR_32_DBL_|0,t/r.TWO_PWR_32_DBL_|0)},r.fromBits=function(t,e){return new r(t,e)},r.fromString=function(t,e){if(0==t.length)throw Error("number format error: empty string");var n=e||10;if(2>n||n>36)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return r.fromString(t.substring(1),n).negate();if(t.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+t);for(var i=r.fromNumber(Math.pow(n,8)),o=r.ZERO,s=0;sa){var f=r.fromNumber(Math.pow(n,a));o=o.multiply(f).add(r.fromNumber(u))}else o=o.multiply(i),o=o.add(r.fromNumber(u))}return o},r.INT_CACHE_={},r.TWO_PWR_16_DBL_=65536,r.TWO_PWR_24_DBL_=1<<24,r.TWO_PWR_32_DBL_=r.TWO_PWR_16_DBL_*r.TWO_PWR_16_DBL_,r.TWO_PWR_31_DBL_=r.TWO_PWR_32_DBL_/2,r.TWO_PWR_48_DBL_=r.TWO_PWR_32_DBL_*r.TWO_PWR_16_DBL_,r.TWO_PWR_64_DBL_=r.TWO_PWR_32_DBL_*r.TWO_PWR_32_DBL_,r.TWO_PWR_63_DBL_=r.TWO_PWR_64_DBL_/2,r.ZERO=r.fromInt(0),r.ONE=r.fromInt(1),r.NEG_ONE=r.fromInt(-1),r.MAX_VALUE=r.fromBits(-1,2147483647),r.MIN_VALUE=r.fromBits(0,-2147483648),r.TWO_PWR_24_=r.fromInt(1<<24),e.exports=r,e.exports.Timestamp=r},{}],62:[function(t,e){function r(t,e){return function r(){return r.hookCalled?void 0:(r.hookCalled=!0,t.apply(e,arguments))}}e.exports={hook:function(t,e,n){if(1!==arguments.length||"object"!=typeof t){var i=this.prototype||this,o=i._pres=i._pres||{},s=i._posts=i._posts||{};return o[t]=o[t]||[],s[t]=s[t]||[],i[t]=function(){var o,s=this,a=arguments[arguments.length-1],u=this._pres[t],f=this._posts[t],c=u.length,h=-1,p=i[t].numAsyncPres,l=function(t){return t?d(t):void(--p||g.apply(s,o))},d=function(t){if("function"==typeof a)return a(t);if(n)return n.call(s,t);throw t},y=function(){if(arguments[0]instanceof Error)return d(arguments[0]);var t,e,n=Array.prototype.slice.call(arguments); -if(!n.length||null==arguments[0]&&"function"==typeof a||(o=n),++h=o)){var e=i[a];if(e.isAsync)e.fn.call(r,function(t){if(t){if(f)return;return f=!0,n(t)}++a,c.apply(r,arguments)},function(t){if(t){if(f)return;return f=!0,n(t)}return 0===--s?n(null):void 0});else if(e.fn.length>0){var h=[function(t){if(t){if(f)return;return f=!0,n(t)}return++a>=o?u>0?void 0:n(null):void c.apply(r,arguments)}];if(arguments.length>=2)for(var p=1;p=o)return u>0?void 0:t.nextTick(function(){n(null)});c()}}};c()},r.prototype.execPost=function(e,r,n,i){var o=this._posts[e]||[],s=o.length,a=0;if(!s)return t.nextTick(function(){i.apply(null,[null].concat(n))});var u=function(){var t=o[a];if(t.length>n.length)t.apply(r,n.concat(function(t){return t?i(t):++a>=s?i.apply(null,[null].concat(n)):void u()}));else{if(t.apply(r,n),++a>=s)return i.apply(null,[null].concat(n));u()}};u()},r.prototype.wrap=function(t,e,r,n,i){var o=n.length>0?n[n.length-1]:null,s=this;this.execPre(t,r,function(a){if(a){if("function"==typeof o)return o(a)}else{var u="function"==typeof o?n.length-1:n.length;e.apply(r,n.slice(0,u).concat(function(){if(arguments[0])return"function"==typeof o?o(arguments[0]):void 0;i&&"function"==typeof o&&o.apply(r,arguments);var e=Array.prototype.slice.call(arguments,1);s.execPost(t,r,e,function(){return arguments[0]?"function"==typeof o?o(arguments[0]):void 0:"function"!=typeof o||i?void 0:o.apply(r,arguments)})}))}})},r.prototype.createWrapper=function(t,e,r){var n=this;return function(){var i=Array.prototype.slice.call(arguments);n.wrap(t,e,r,i)}},r.prototype.pre=function(t,e,r,n){"boolean"!=typeof arguments[1]&&(n=r,r=e,e=!1),this._pres[t]=this._pres[t]||[];var i=this._pres[t];return e&&(i.numAsync=i.numAsync||0,++i.numAsync),i.push({fn:r,isAsync:e}),this},r.prototype.post=function(t,e){return(this._posts[t]=this._posts[t]||[]).push(e),this},r.prototype.clone=function(){var t=new r;for(var e in this._pres)t._pres[e]=this._pres[e].slice();for(var e in this._posts)t._posts[e]=this._posts[e].slice();return t},e.exports=r}).call(this,t("FWaASH"))},{FWaASH:46}],64:[function(t,e,r){e.exports=r=t("./lib")},{"./lib":65}],65:[function(t,e,r){function n(t){return t}r.get=function(t,e,i,o){"function"==typeof i&&(o=i,i=void 0),o||(o=n);var s="string"==typeof t?t.split("."):t;if(!Array.isArray(s))throw new TypeError("Invalid `path`. Must be either string or array");for(var a,u=e,f=0;fp;++p)if(f=u[p],"$"!=f){if(Array.isArray(h)&&!/^\d+$/.test(f)){var d=u.slice(p);if(!c&&Array.isArray(e))for(var y=0;y0},o.prototype.onReject=function(t){if(!t)return this;if("function"!=typeof t)throw new TypeError("fn should be a function");return this.on(o.FAILURE,t)},o.prototype.onResolve=function(t){if(this.end(),!t)return this;if("function"!=typeof t)throw new TypeError("fn should be a function");return this.on(o.FAILURE,function(e){t.call(this,e)}),this.on(o.SUCCESS,function(){t.apply(this,i(null,arguments))}),this},o.prototype.then=function(t,e){var r=new o;return this.onFulfill("function"==typeof t?s(r,t):r.fulfill.bind(r)),this.onReject("function"==typeof e?s(r,e):r.reject.bind(r)),r},o.prototype.end=function(t){return this.onReject(t),this.ended=!0,this},o.trace=function(t,e){t.then(function(){console.log("%s fulfill %j",e,n(arguments))},function(){console.log("%s reject %j",e,n(arguments))})},o.prototype.chain=function(t){var e=this;return e.onFulfill(t.fulfill.bind(t)),e.onReject(t.reject.bind(t)),t},o.prototype.all=function(t){var e=new o;return this.then(t).then(function(t){var r,n=0,i=[];return t.length||e.resolve(),t.forEach(function(t,o){r||(n++,t.then(function(t){r||(i[o]=t,--n,0==n&&e.fulfill(i))},function(t){r||(r=t,e.reject(t))}))}),e},e.reject.bind(e)),e},o.hook=function(t){var e=new o,r=new o,n=function(){return--i,0==i&&r.fulfill(),r},i=1,s=e;return t.forEach(function(t){s=s.then(function(){var e=new o;return i++,t(e.resolve.bind(e),n),e})}),s=s.then(n),e.resolve(),s},o.fulfilled=function(){var t=new o;return t.fulfill.apply(t,arguments),t},o.rejected=function(t){return(new o).reject(t)},o.deferred=function(){var t=new o;return{promise:t,reject:t.reject.bind(t),resolve:t.fulfill.bind(t),callback:t.resolve.bind(t)}}}).call(this,t("FWaASH"))},{FWaASH:46,events:44,util:48}],67:[function(t,e){!function(t){function r(t){return t==Number(t)?Number(t):(n.exec(t.toLowerCase()),RegExp.$1*i[RegExp.$2])}var n=/(\d*.?\d+)([mshd]+)/,i={};i.ms=1,i.s=1e3,i.m=60*i.s,i.h=60*i.m,i.d=24*i.h,t.top?t.ms=r:e.exports=r}(this)},{}],68:[function(t,e,r){function n(t){return"object"==typeof t&&"[object RegExp]"==i.call(t)}var i=Object.prototype.toString;e.exports=r=function(t){if(!n(t))throw new TypeError("Not a RegExp");var e=[];return t.global&&e.push("g"),t.multiline&&e.push("m"),t.ignoreCase&&e.push("i"),new RegExp(t.source,e.join(""))}},{}],69:[function(t,e,r){e.exports=r=t("./lib/sliced")},{"./lib/sliced":70}],70:[function(t,e){e.exports=function(t,e,r){var n=[],i=t.length;if(0===i)return n;var o=0>e?Math.max(0,e+i):e||0;for(void 0!==r&&(i=0>r?r+i:r);i-->o;)n[i-o]=t[i];return n}},{}]},{},[1]); \ No newline at end of file +!function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var c=r[s]={exports:{}};e[s][0].call(c.exports,function(t){var r=e[s][1][t];return i(r?r:t)},c,c.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;so;++o)Object.defineProperty(r,i[o],{enumerable:!1,writable:!0,configurable:!0,value:void 0});Object.defineProperty(r,"toObject",{enumerable:!0,configurable:!0,writable:!1,value:function(){return t.get(c)}}),Object.defineProperty(r,"toJSON",{enumerable:!0,configurable:!0,writable:!1,value:function(){return t.get(c)}}),Object.defineProperty(r,"$__isNested",{enumerable:!0,configurable:!0,writable:!1,value:!0}),a(e,r,c,s),this.$__.getters[c]=r}return this.$__.getters[c]},set:function(t){return t instanceof o&&(t=t.toObject()),(this.$__.scope||this).set(c,t)}}):Object.defineProperty(r,t,{enumerable:!0,configurable:!0,get:function(){return this.get.call(this.$__.scope||this,c)},set:function(t){return this.set.call(this.$__.scope||this,c,t)}})}function f(t){for(var e,r,n,i=Object.keys(t),o=i.length;o--;)r=i[o],n=t[r],E.isObject(n)&&(t[r]=f(n)),void 0!==t[r]?e=!0:delete t[r];return e?t:void 0}function l(t,e,r,n){for(var i,o=t.schema,s=Object.keys(o[r]),a=s.length;a--;){i=s[a];for(var u,c=i.split("."),f=c.length,l=f-1,h=e,p=0;f>p;++p)u=c[p],p===l?h[u]=O(t.get(i),n):h=h[u]||(h[u]={})}return e}var h,p,d,_=t("events").EventEmitter,y=t("./error"),g=t("./schema/mixed"),v=t("./schema"),m=t("./error/objectExpected"),b=t("./error/strict"),w=t("./schematype").ValidatorError,E=t("./utils"),O=E.clone,A=E.isMongooseObject,S=t("util").inspect,j=y.ValidationError,N=t("./internal"),x=E.deepEqual,B=t("hooks-fixed"),T=t("./promise_provider");E.each(["on","once","emit","listeners","removeListener","setMaxListeners","removeAllListeners","addListener"],function(t){o.prototype[t]=function(){return this.$__.emitter[t].apply(this.$__.emitter,arguments)}}),o.prototype.constructor=o,o.prototype.schema,o.prototype.isNew,o.prototype.id,o.prototype.errors,o.prototype.$__buildDoc=function(t,e,r){var n,i,o={},s=null,a=this;if(e&&"Object"===E.getFunctionName(e.constructor))if(n=Object.keys(e),i=n.length,1===i&&"_id"===n[0])s=!!e[n[i]];else for(;i--;)if("_id"!==n[i]&&(!e[n[i]]||"object"!=typeof e[n[i]])){s=!e[n[i]];break}for(var u=Object.keys(this.schema.paths),c=u.length,f=0;c>f;++f){var l=u[f];if("_id"===l){if(r)continue;if(t&&"_id"in t)continue}for(var h=this.schema.paths[l],p=l.split("."),d=p.length,_=d-1,y="",g=o,v=0,m=!1;d>v;++v){var b,w=p[v];if(y+=w,s===!0){if(y in e)break}else e&&y in e&&(m=!0);if(v===_)if(e&&null!==s)if(s===!0){if(l in e)continue;b=h.getDefault(a,!0),"undefined"!=typeof b&&(g[w]=b,a.$__.activePaths.default(l))}else m&&(b=h.getDefault(a,!0),"undefined"!=typeof b&&(g[w]=b,a.$__.activePaths.default(l)));else b=h.getDefault(a,!0),"undefined"!=typeof b&&(g[w]=b,a.$__.activePaths.default(l));else g=g[w]||(g[w]={}),y+="."}}return o},o.prototype.init=function(t,e,r){if("function"==typeof e&&(r=e,e=null),this.isNew=!1,null!==t._id&&void 0!==t._id&&e&&e.populated&&e.populated.length)for(var n=String(t._id),i=0;io;++o)e=this.getValue(n[o]),A(e)?r[n[o]]=e.toObject({depopulate:!0}):null===e||void 0===e||!e.valueOf||e.constructor&&"Date"===E.getFunctionName(e.constructor)?r[n[o]]=e:r[n[o]]=e.valueOf()};for(var k in B)"pre"===k||"post"===k?o.prototype["$"+k]=o["$"+k]=B[k]:o.prototype[k]=o[k]=B[k];o.prototype.update=function(){var t=E.args(arguments);return t.unshift({_id:this._id}),this.constructor.update.apply(this.constructor,t)},o.prototype.set=function(t,e,r,n){r&&"Object"===E.getFunctionName(r.constructor)&&(n=r,r=void 0);var i,s=n&&n.merge,a=r&&r!==!0,u=r===!0,c=n&&"strict"in n?n.strict:this.$__.strictMode;if(a&&(i=this.$__.adhocPaths||(this.$__.adhocPaths={}),i[t]=v.interpretAsType(t,r,this.schema.options)),"string"!=typeof t){if(null!==t&&void 0!==t){var f=e?e+".":"";t instanceof o&&(t=t.$__isNested?t.toObject():t._doc);for(var l,h,p=Object.keys(t),d=p.length;d--;){h=p[d];var _=f+h;if(l=this.schema.pathType(_),null===t[h]||void 0===t[h]||!E.isObject(t[h])||t[h].constructor&&"Object"!==E.getFunctionName(t[h].constructor)||"virtual"===l||"real"===l||this.$__path(_)instanceof g||this.schema.paths[_]&&this.schema.paths[_].options&&this.schema.paths[_].options.ref)if(c){if(u&&void 0===t[h]&&void 0!==this.get(h))continue;if("real"===l||"virtual"===l)this.schema.paths[_]&&this.schema.paths[_].$isSingleNested&&t[h]instanceof o&&(t[h]=t[h].toObject({virtuals:!1})),this.set(f+h,t[h],u);else if("nested"===l&&t[h]instanceof o)this.set(f+h,t[h].toObject({virtuals:!1}),u);else if("throw"===c)throw"nested"===l?new m(h,t[h]):new b(h)}else void 0!==t[h]&&this.set(f+h,t[h],u);else this.set(t[h],f+h,u)}return this}var w=t;t=e,e=w}var O=this.schema.pathType(t);if("nested"===O&&e)return!E.isObject(e)||e.constructor&&"Object"!==E.getFunctionName(e.constructor)?(this.invalidate(t,new y.CastError("Object",e,t)),this):(s||this.setValue(t,null),this.set(e,t,u),this);var A,S=t.split(".");if("adhocOrUndefined"===O&&c){var j;for(d=0;d0&&e[0]instanceof o&&e[0].constructor.modelName&&A.options.type[0].ref===e[0].constructor.modelName&&(this.ownerDocument?($={model:e[0].constructor},this.ownerDocument().populated(this.$__fullPath(t),e.map(function(t){return t._id}),$)):($={model:e[0].constructor},this.populated(t,e.map(function(t){return t._id}),$)),k=!0),e=A.applySetters(e,this,!1,B),!k&&this.$__.populated&&delete this.$__.populated[t],this.$markValid(t)}catch(r){var I;r instanceof y.CastError||(I=r),this.invalidate(t,new y.CastError(A.instance,e,t,I)),T=!1}return T&&this.$__set(x,t,u,S,A,e,B),this},o.prototype.$__shouldModify=function(t,e,r,n,i,s,a){return this.isNew?!0:void 0!==s||this.isSelected(e)?void 0===s&&e in this.$__.activePaths.states.default?!1:this.populated(e)&&s instanceof o&&x(s._id,a)?!1:x(s,a||this.get(e))?!r&&null!==s&&void 0!==s&&e in this.$__.activePaths.states.default&&x(s,i.getDefault(this,r))?!0:!1:!0:!0},o.prototype.$__set=function(e,r,n,i,o,s,a){d=d||t("./types/embedded");var u=this.$__shouldModify(e,r,n,i,o,s,a),c=this;u&&(this.markModified(e,s),p||(p=t("./types/array")),s&&s.isMongooseArray&&(s._registerAtomic("$set",s),this.$__.activePaths.forEach(function(t){0===t.indexOf(r+".")&&c.$__.activePaths.ignore(t)})));for(var f=this._doc,l=0,h=i.length;h>l;l++){var _=l+1,y=_===h;y?f[i[l]]=s:f=f[i[l]]&&"Object"===E.getFunctionName(f[i[l]].constructor)?f[i[l]]:f[i[l]]&&f[i[l]]instanceof d?f[i[l]]:f[i[l]]&&f[i[l]].$isSingleNested?f[i[l]]:f[i[l]]&&Array.isArray(f[i[l]])?f[i[l]]:f[i[l]]={}}},o.prototype.getValue=function(t){return E.getValue(t,this._doc)},o.prototype.setValue=function(t,e){return E.setValue(t,e,this._doc),this},o.prototype.get=function(t,e){var r;e&&(r=v.interpretAsType(t,e,this.schema.options));for(var n=this.$__path(t)||this.schema.virtualpath(t),i=t.split("."),o=this._doc,s=0,a=i.length;a>s;s++)o=null===o||void 0===o?void 0:o[i[s]];return r&&(o=r.cast(o)),n&&!this.populated(t)&&(o=n.applyGetters(o,this)),o},o.prototype.$__path=function(t){var e=this.$__.adhocPaths,r=e&&e[t];return r?r:this.schema.path(t)},o.prototype.markModified=function(t){this.$__.activePaths.modify(t)},o.prototype.modifiedPaths=function(){var t=Object.keys(this.$__.activePaths.states.modify);return t.reduce(function(t,e){var r=e.split(".");return t.concat(r.reduce(function(t,e,n){return t.concat(r.slice(0,n).concat(e).join("."))},[]))},[])},o.prototype.isModified=function(t){return t?!!~this.modifiedPaths().indexOf(t):this.$__.activePaths.some("modify")},o.prototype.$isDefault=function(t){return t in this.$__.activePaths.states.default},o.prototype.isDirectModified=function(t){return t in this.$__.activePaths.states.modify},o.prototype.isInit=function(t){return t in this.$__.activePaths.states.init},o.prototype.isSelected=function(t){if(this.$__.selected){if("_id"===t)return 0!==this.$__.selected._id;var e,r=Object.keys(this.$__.selected),n=r.length,i=!1;if(1===n&&"_id"===r[0])return 0===this.$__.selected._id;for(;n--;)if(e=r[n],"_id"!==e){i=!!this.$__.selected[e];break}if(t in this.$__.selected)return i;n=r.length;for(var o=t+".";n--;)if(e=r[n],"_id"!==e){if(0===e.indexOf(o))return i;if(0===o.indexOf(e+"."))return i}return!i}return!0},o.prototype.validate=function(t,e){var r=this,n=T.get();return"function"==typeof t&&(e=t,t=null),t&&t.__noPromise?void this.$__validate(e):new n.ES6(function(t,n){r.$__validate(function(r){return e&&e(r),r?void n(r):void t()})})},o.prototype.$__validate=function(t){var e=this,r=function(){var t=e.$__.validationError;if(e.$__.validationError=void 0,e.emit("validate",e),t){for(var r in t.errors)!e.__parent&&t.errors[r]instanceof y.CastError&&e.invalidate(r,t.errors[r]);return t}},o=Object.keys(this.$__.activePaths.states.require).filter(function(t){return e.isSelected(t)||e.isModified(t)?!0:!1});o=o.concat(Object.keys(this.$__.activePaths.states.init)),o=o.concat(Object.keys(this.$__.activePaths.states.modify)),o=o.concat(Object.keys(this.$__.activePaths.states.default)),0===o.length&&n.nextTick(function(){var e=r();return e?void t(e):void t()});for(var s={},a=0,u=0;uh;++h)o.push(c+"."+h)}var p=function(){var e=r();return e?void t(e):void t()},d=function(t){s[t]||(s[t]=!0,a++,n.nextTick(function(){var r=e.schema.path(t);if(!r)return--a||p();if(!e.$isValid(t))return void(--a||p());var n=e.getValue(t);r.doValidate(n,function(r){r&&e.invalidate(t,r,void 0,!0),--a||p()},e)}))};o.forEach(d)},o.prototype.validateSync=function(t){var e=this;"string"==typeof t&&(t=t.split(" "));var r=Object.keys(this.$__.activePaths.states.require).filter(function(t){return e.isSelected(t)||e.isModified(t)?!0:!1});if(r=r.concat(Object.keys(this.$__.activePaths.states.init)),r=r.concat(Object.keys(this.$__.activePaths.states.modify)),r=r.concat(Object.keys(this.$__.activePaths.states.default)),t&&t.length){for(var n=[],i=0;ie.path?1:0});var r,n,i=[];return e.forEach(function(t){t&&(0!==t.path.indexOf(r)?(r=t.path+".",i.push(t),n=t):n.value&&n.value._atomics&&n.value.hasAtomics()&&(n.value._atomics={},n.value._atomics.$set=n.value))}),n=r=null,i},o.prototype.$__setSchema=function(t){a(t.tree,this,void 0,t.options),this.schema=t},o.prototype.$__getArrayPathsToValidate=function(){return h||(h=t("./types/documentarray")),this.$__.activePaths.map("init","modify",function(t){return this.getValue(t)}.bind(this)).filter(function(t){return t&&t instanceof Array&&t.isMongooseDocumentArray&&t.length}).reduce(function(t,e){return t.concat(e)},[]).filter(function(t){return t})},o.prototype.$__getAllSubdocs=function(){function e(t,r){var n=this[r];return n instanceof d&&t.push(n),n&&n.$isSingleNested&&(t=Object.keys(n._doc).reduce(e.bind(n._doc),t),t.push(n)),n&&n.isMongooseDocumentArray?n.forEach(function(r){r&&r._doc&&(r instanceof d&&t.push(r),t=Object.keys(r._doc).reduce(e.bind(r._doc),t))}):n instanceof o&&n.$__isNested&&(n=n.toObject(),n&&(t=Object.keys(n).reduce(e.bind(n),t))),t}h||(h=t("./types/documentarray")),d=d||t("./types/embedded");var r=Object.keys(this._doc).reduce(e.bind(this),[]);return r},o.prototype.$__registerHooksFromSchema=function(){d=d||t("./types/embedded");var e=T.get(),r=this,n=r.schema&&r.schema.callQueue;if(!n.length)return r;var i=n.reduce(function(t,e){if("pre"!==e[0]&&"post"!==e[0]&&"on"!==e[0])return r[e[0]].apply(r,e[1]),t;var n=[].slice.call(e[1]),i="on"===e[0]?"post":n[0];return i in t||(t[i]={post:[],pre:[]}),"post"===e[0]?t[i].post.push(n):"on"===e[0]?t[i].push(n):t[i].pre.push(n),t},{post:[]});return i.post.forEach(function(t){r.on.apply(r,t)}),delete i.post,i.init&&r instanceof d?(i.init.pre&&i.init.pre.forEach(function(t){r.$pre.apply(r,t)}),i.init.post&&i.init.post.forEach(function(t){r.$post.apply(r,t)}),delete i.init):i.set&&(i.set.pre&&i.set.pre.forEach(function(t){r.$pre.apply(r,t)}),i.set.post&&i.set.post.forEach(function(t){r.$post.apply(r,t)}),delete i.set),Object.keys(i).forEach(function(t){var n="$__original_"+t;r[t]&&(r[n]=r[t],r[t]=function(){var t,i=[].slice.call(arguments),o=i.pop();return new e.ES6(function(e,s){o&&"function"!=typeof o?i.push(o):t=o,i.push(function(n,i){return n?(r.$__handleReject(n),t&&t(n),void s(n)):(t&&t.apply(null,[null].concat(Array.prototype.slice.call(arguments,1))),void e(i))}),r[n].apply(r,i)})},i[t].pre.forEach(function(t){t[0]=n,r.$pre.apply(r,t)}),i[t].post.forEach(function(t){t[0]=n,r.$post.apply(r,t)}))}),r},o.prototype.$__handleReject=function(t){this.listeners("error").length?this.emit("error",t):this.constructor.listeners&&this.constructor.listeners("error").length?this.constructor.emit("error",t):this.listeners&&this.listeners("error").length&&this.emit("error",t)},o.prototype.$toObject=function(t,e){var r={transform:!0,json:e};if(t&&t.depopulate&&!t._skipDepopulateTopLevel&&this.$__.wasPopulated)return O(this._id,t);t&&t._skipDepopulateTopLevel&&(t._skipDepopulateTopLevel=!1),(!t||"Object"!==E.getFunctionName(t.constructor)||t&&t._useSchemaOptions)&&(e?(t=this.schema.options.toJSON?O(this.schema.options.toJSON):{},t.json=!0,t._useSchemaOptions=!0):(t=this.schema.options.toObject?O(this.schema.options.toObject):{},t.json=!1,t._useSchemaOptions=!0));for(var n in r)void 0===t[n]&&(t[n]=r[n]);"minimize"in t||(t.minimize=this.schema.options.minimize);var i=t.transform,o=O(this._doc,t)||{};t.getters&&(l(this,o,"paths",t),t.minimize&&(o=f(o)||{})),(t.virtuals||t.getters&&t.virtuals!==!1)&&l(this,o,"virtuals",t),t.versionKey===!1&&this.schema.options.versionKey&&delete o[this.schema.options.versionKey];var s=t.transform;if(s===!0||this.schema.options.toObject&&s){var a=t.json?this.schema.options.toJSON:this.schema.options.toObject;a&&(s="function"==typeof t.transform?t.transform:a.transform)}else t.transform=i;if("function"==typeof s){var u=s(this,o,t);"undefined"!=typeof u&&(o=u)}return o},o.prototype.toObject=function(t){return this.$toObject(t)},o.prototype.toJSON=function(t){return this.$toObject(t,!0)},o.prototype.inspect=function(t){var e,r=t&&"Object"===E.getFunctionName(t.constructor);return e=r?t:this.schema.options.toObject?O(this.schema.options.toObject):{},e.minimize=!1,e.retainKeyOrder=!0,this.toObject(e)},o.prototype.toString=function(){return S(this.inspect())},o.prototype.equals=function(t){var e=this.get("_id"),r=t.get?t.get("_id"):t;return e||r?e&&e.equals?e.equals(r):e===r:x(this,t)},o.prototype.populate=function(){if(0===arguments.length)return this;var t,e=this.$__.populate||(this.$__.populate={}),r=E.args(arguments);if("function"==typeof r[r.length-1]&&(t=r.pop()),r.length)for(var n=E.populate.apply(null,r),i=0;in;++n)t(e[n],this.paths[e[n]]);return this},i.prototype.requiredPaths=function(t){if(this._requiredpaths&&!t)return this._requiredpaths;for(var e=Object.keys(this.paths),r=e.length,n=[];r--;){var i=e[r];this.paths[i].isRequired&&n.push(i)}return this._requiredpaths=n,this._requiredpaths},i.prototype.indexedPaths=function(){return this._indexedpaths?this._indexedpaths:(this._indexedpaths=this.indexes(),this._indexedpaths)},i.prototype.pathType=function(t){return t in this.paths?"real":t in this.virtuals?"virtual":t in this.nested?"nested":t in this.subpaths?"real":t in this.singleNestedPaths?"real":/\.\d+\.|\.\d+$/.test(t)?s(this,t):"adhocOrUndefined"},i.prototype.hasMixedParent=function(t){var e=t.split(/\./g);t="";for(var r=0;r0?t+"."+e[r]:e[r],t in this.paths&&this.paths[t]instanceof u.Mixed)return!0;return!1},i.prototype.setupTimestamp=function(t){if(t){var e=t.createdAt||"createdAt",r=t.updatedAt||"updatedAt",n={};n[r]=Date,this.paths[e]||(n[e]=Date),this.add(n),this.pre("save",function(t){var n=new Date,i=this._id&&this._id.auto;this[e]||(this[e]=i?this._id.getTimestamp():n),(this.isNew||this.isModified())&&(this[r]=this.isNew?this[e]:n),t()});var i=function(){var t=new Date,n={$set:{},$setOnInsert:{}};return n.$set[r]=t,n.$setOnInsert[e]=t,n};this.pre("findOneAndUpdate",function(t){this.findOneAndUpdate({},i()),t()}),this.pre("update",function(t){this.update({},i()),t()})}},i.prototype.queue=function(t,e){return this.callQueue.push([t,e]),this},i.prototype.pre=function(){var t=arguments[0];return _[t]?(this.s.hooks.pre.apply(this.s.hooks,arguments),this):this.queue("pre",arguments)},i.prototype.post=function(t,e){return _[t]?(this.s.hooks.post.apply(this.s.hooks,arguments),this):e.length<2?this.queue("on",[arguments[0],function(t){return e.call(t,t)}]):this.queue("post",[arguments[0],function(t){var r=this,n=Array.prototype.slice.call(arguments,1);e.call(this,this,function(e){return t.apply(r,[e].concat(n))})}])},i.prototype.plugin=function(t,e){return t(this,e),this},i.prototype.method=function(t,e){if("string"!=typeof t)for(var r in t)this.methods[r]=t[r];else this.methods[t]=e;return this},i.prototype.static=function(t,e){if("string"!=typeof t)for(var r in t)this.statics[r]=t[r];else this.statics[t]=e;return this},i.prototype.index=function(t,e){return e||(e={}),e.expires&&h.expires(e),this._indexes.push([t,e]),this},i.prototype.set=function(t,e,r){if(1===arguments.length)return this.options[t];switch(t){case"read":this.options[t]=c(e,r);break;case"safe":this.options[t]=e===!1?{w:0}:e;break;case"timestamps":this.setupTimestamp(e),this.options[t]=e;break;default:this.options[t]=e}return this},i.prototype.get=function(t){return this.options[t]};var v="2d 2dsphere hashed text".split(" ");Object.defineProperty(i,"indexTypes",{get:function(){return v},set:function(){throw new Error("Cannot overwrite Schema.indexTypes")}}),i.prototype.indexes=function(){"use strict";function t(t,r){var n,i,o,s,a,u,c=t._indexes,f=c.length,l=0;for(l=0;f>l;++l){for(n=c[l][0],s=Object.keys(n),o=s.length,i={},u=0;o>u;++u)a=s[u],i[r+a]=n[a];e.push([i,c[l][1]])}}var e=[],r={},n=function(o,s){if(!r[s]){r[s]=!0,s=s||"";for(var a,c,f,l,p,d,_,y=Object.keys(o.paths),g=0;go;++o)e=n[o],r=t[e],0===e.indexOf("$")&&r&&(t[e]=this.castForQuery(e,r));return v(this.casterConstructor.schema,t)}function l(t){var e=t.$geometry;if(e)return a(t,this),t}var h=t("../schematype"),p=h.CastError,d={Boolean:t("./boolean"),Date:t("./date"),Number:t("./number"),String:t("./string"),ObjectId:t("./objectid"),Buffer:t("./buffer")},_=t("../types").Array,y=t("../types").Embedded,g=t("./mixed"),v=t("../cast"),m=t("../utils"),b=m.isMongooseObject;n.schemaName="Array",n.prototype=Object.create(h.prototype),n.prototype.constructor=n,n.prototype.checkRequired=function(t){return!(!t||!t.length)},n.prototype.applyGetters=function(t,e){return this.caster.options&&this.caster.options.ref?t:h.prototype.applyGetters.call(this,t,e)},n.prototype.cast=function(t,e,r){if(Array.isArray(t)){if(!t.length&&e)for(var n=e.schema.indexedPaths(),i=0,o=n.length;o>i;++i){var s=n[i][0][this.path];if("2dsphere"===s||"2d"===s)return}if(t&&t.isMongooseArray||(t=new _(t,this.path,e)),this.caster)try{for(i=0,o=t.length;o>i;i++)t[i]=this.caster.cast(t[i],e,r)}catch(e){throw new p(e.type,t,this.path,e)}return t}return e&&r&&e.markModified(this.path),this.cast([t],e,r)},n.prototype.castForQuery=function(t,e){var r,n;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Array.");n=r.call(this,e)}else{n=t;var i=this.casterConstructor.prototype,o=i.castForQuery||i.cast,s=this.caster;Array.isArray(n)?n=n.map(function(t){return m.isObject(t)&&t.$elemMatch?t:(o&&(t=o.call(s,t)),b(t)?t.toObject({virtuals:!1}):t)}):o&&(n=o.call(s,n))}return n&&b(n)?n.toObject({virtuals:!1}):n};var w=n.prototype.$conditionalHandlers={};w.$all=c,w.$options=String,w.$elemMatch=f,w.$geoIntersects=l,w.$or=w.$and=function(t){if(!Array.isArray(t))throw new TypeError("conditional $or/$and require array");for(var e=[],r=0;r=r.valueOf()},message:r,type:"min",min:t})}return this},n.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxValidator},this)),t){var r=e||o.Date.max;r=r.replace(/{MAX}/,t===Date.now?"Date.now()":this.cast(t).toString());var n=this;this.validators.push({validator:this.maxValidator=function(e){var r=t===Date.now?t():n.cast(t);return null===e||e.valueOf()<=r.valueOf()},message:r,type:"max",max:t})}return this},n.prototype.cast=function(t){if(null===t||void 0===t||""===t)return null;if(t instanceof Date)return t;var e;if("boolean"==typeof t)throw new u("date",t,this.path);if(t instanceof Number||"number"==typeof t||String(t)==Number(t)?e=new Date(Number(t)):t.valueOf&&(e=new Date(t.valueOf())),!isNaN(e.valueOf()))return e;throw new u("date",t,this.path)},n.prototype.$conditionalHandlers=s.options(a.prototype.$conditionalHandlers,{$gt:i,$gte:i,$lt:i,$lte:i}),n.prototype.castForQuery=function(t,e){var r;if(2!==arguments.length)return this.cast(t);if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Date.");return r.call(this,e)},e.exports=n},{"../error":12,"../schematype":39,"../utils":48}],31:[function(t,e,r){function n(t,e,r){function n(){c.apply(this,arguments)}n.prototype=Object.create(c.prototype),n.prototype.$__setSchema(e),n.schema=e;for(var i in e.methods)n.prototype[i]=e.methods[i];for(i in e.statics)n[i]=e.statics[i];n.options=r,o.call(this,t,n,r),this.schema=e;var s=this.path,u=this.defaultValue;this.default(function(){var t=u.call(this);return Array.isArray(t)||(t=[t]),new a(t,s,this)})}function i(t,e,r){if(r&&e){for(var n,i,o=t.path+".",s=Object.keys(e),a=s.length,u={};a--;)i=s[a],0===i.indexOf(o)&&(n||(n=!0),u[i.substring(o.length)]=e[i]);return n&&u||void 0}}var o=t("./array"),s=t("../error/cast"),a=t("../types/documentarray"),u=t("../schematype"),c=t("../types/embedded");n.schemaName="DocumentArray",n.prototype=Object.create(o.prototype),n.prototype.constructor=n,n.prototype.doValidate=function(t,e,r,n){u.prototype.doValidate.call(this,t,function(r){function i(t){t&&(o=t),--s||e(o)}if(r)return e(r);var o,s=t&&t.length;if(!s)return e();if(n&&n.updateValidator)return e();for(var a=0,u=s;u>a;++a){var c=t[a];c?c.$__original_validate?c.$__original_validate({__noPromise:!0},i):c.validate({__noPromise:!0},i):--s||e(o)}},r)},n.prototype.doValidateSync=function(t,e){var r=u.prototype.doValidateSync.call(this,t,e);if(r)return r;var n=t&&t.length,i=null;if(n){for(var o=0,s=n;s>o&&!i;++o){var a=t[o];if(a){var c=a.validateSync();c&&(i=c)}}return i}},n.prototype.cast=function(t,e,r,n,o){var u,f,l;if(!Array.isArray(t))return e&&r&&e.markModified(this.path),this.cast([t],e,r,n);if(!(t&&t.isMongooseDocumentArray||o&&o.skipDocumentArrayCast)&&(t=new a(t,this.path,e),n&&n._handlers))for(var h in n._handlers)e.removeListener(h,n._handlers[h]);for(l=t.length;l--;)if(t[l]&&(t[l]instanceof c&&t[l].schema!==this.casterConstructor.schema&&(t[l]=t[l].toObject({virtuals:!1})),!(t[l]instanceof c)&&t[l]))if(r)u||(u=i(this,e.$__.selected,r)),f=new this.casterConstructor(null,t,!0,u,l),t[l]=f.init(t[l]);else{try{f=n.id(t[l]._id)}catch(t){}if(n&&f)f.set(t[l]),t[l]=f;else try{f=new this.casterConstructor(t[l],t,void 0,void 0,l),t[l]=f}catch(e){throw new s("embedded",t[l],t._path,e)}}return t},e.exports=n},{"../error/cast":13,"../schematype":39,"../types/documentarray":43,"../types/embedded":44,"./array":27}],32:[function(t,e,r){function n(t,e,r){var n=function(t,e,r){var n=this;o.apply(this,arguments),this.$parent=r,r&&r.on("save",function(){n.emit("save",n)})};n.prototype=Object.create(o.prototype),n.prototype.$__setSchema(t),n.schema=t,n.$isSingleNested=!0,n.prototype.$basePath=e;for(var s in t.methods)n.prototype[s]=t.methods[s];for(s in t.statics)n[s]=t.statics[s];this.caster=n,this.schema=t,this.$isSingleNested=!0,i.call(this,e,r,"Embedded")}var i=t("../schematype"),o=t("../types/subdocument");e.exports=n,n.prototype=Object.create(i.prototype),n.prototype.$conditionalHandlers.$geoWithin=function(t){return{$geometry:this.castForQuery(t.$geometry)}},n.prototype.cast=function(t,e,r){if(t&&t.$isSingleNested)return t;var n=new this.caster(void 0,e?e.$__.selected:void 0,e);return r?n.init(t):n.set(t,void 0,!0),n},n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t);return r.call(this,e)}return e=t,new this.caster(e).toObject({virtuals:!1})},n.prototype.doValidate=function(t,e){i.prototype.doValidate.call(this,t,function(r){return r?e(r):t?void t.validate(e,{__noPromise:!0}):e(null)})},n.prototype.doValidateSync=function(t){var e=i.prototype.doValidateSync.call(this,t);if(e)return e;if(t)return t.validateSync()}},{"../schematype":39,"../types/subdocument":47}],33:[function(t,e,r){r.String=t("./string"),r.Number=t("./number"),r.Boolean=t("./boolean"),r.DocumentArray=t("./documentarray"),r.Embedded=t("./embedded"),r.Array=t("./array"),r.Buffer=t("./buffer"),r.Date=t("./date"),r.ObjectId=t("./objectid"),r.Mixed=t("./mixed"),r.Oid=r.ObjectId,r.Object=r.Mixed,r.Bool=r.Boolean},{"./array":27,"./boolean":28,"./buffer":29,"./date":30,"./documentarray":31,"./embedded":32,"./mixed":34,"./number":35,"./objectid":36,"./string":38}],34:[function(t,e,r){function n(t,e){if(e&&e.default){var r=e.default;Array.isArray(r)&&0===r.length?e.default=Array:!e.shared&&o.isObject(r)&&0===Object.keys(r).length&&(e.default=function(){return{}})}i.call(this,t,e,"Mixed")}var i=t("../schematype"),o=t("../utils");n.schemaName="Mixed",n.prototype=Object.create(i.prototype),n.prototype.constructor=n,n.prototype.cast=function(t){return t},n.prototype.castForQuery=function(t,e){return 2===arguments.length?e:t},e.exports=n},{"../schematype":39,"../utils":48}],35:[function(t,e,r){(function(r){function n(t,e){a.call(this,t,e,"Number")}function i(t){return this.cast(t)}function o(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.cast(t)}):[this.cast(t)]}var s,a=t("../schematype"),u=a.CastError,c=t("./operators/bitwise"),f=t("../error").messages,l=t("../utils");n.schemaName="Number",n.prototype=Object.create(a.prototype),n.prototype.constructor=n,n.prototype.checkRequired=function(t,e){return a._isRef(this,t,e,!0)?!!t:"number"==typeof t||t instanceof Number},n.prototype.min=function(t,e){if(this.minValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.minValidator},this)),null!==t&&void 0!==t){var r=e||f.Number.min;r=r.replace(/{MIN}/,t),this.validators.push({validator:this.minValidator=function(e){return null==e||e>=t},message:r,type:"min",min:t})}return this},n.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxValidator},this)),null!==t&&void 0!==t){var r=e||f.Number.max;r=r.replace(/{MAX}/,t),this.validators.push({validator:this.maxValidator=function(e){return null==e||t>=e},message:r,type:"max",max:t})}return this},n.prototype.cast=function(e,n,i){if(a._isRef(this,e,n,i)){if(null===e||void 0===e)return e;if(s||(s=t("./../document")),e instanceof s)return e.$__.wasPopulated=!0,e;if("number"==typeof e)return e;if(r.isBuffer(e)||!l.isObject(e))throw new u("number",e,this.path);var o=n.$__fullPath(this.path),c=n.ownerDocument?n.ownerDocument():n,f=c.populated(o,!0),h=new f.options.model(e);return h.$__.wasPopulated=!0,h}var p=e&&e._id?e._id:e;if(!isNaN(p)){if(null===p)return p;if(""===p)return null;if(("string"==typeof p||"boolean"==typeof p)&&(p=Number(p)),p instanceof Number)return p;if("number"==typeof p)return p;if(p.toString&&!Array.isArray(p)&&p.toString()==Number(p))return new Number(p)}throw new u("number",e,this.path)},n.prototype.$conditionalHandlers=l.options(a.prototype.$conditionalHandlers,{$bitsAllClear:c,$bitsAnyClear:c,$bitsAllSet:c,$bitsAnySet:c,$gt:i,$gte:i,$lt:i,$lte:i,$mod:o}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with Number.");return r.call(this,e)}return e=this.cast(t)},e.exports=n}).call(this,t("buffer").Buffer)},{"../error":12,"../schematype":39,"../utils":48,"./../document":5,"./operators/bitwise":37,buffer:71}],36:[function(t,e,r){(function(r){function n(t,e){u.call(this,t,e,"ObjectID")}function i(t){return this.cast(t)}function o(){return new f}function s(t){return this.$__._id=null,t}var a,u=t("../schematype"),c=u.CastError,f=t("../types/objectid"),l=t("../utils");n.schemaName="ObjectId",n.prototype=Object.create(u.prototype),n.prototype.constructor=n,n.prototype.auto=function(t){return t&&(this.default(o),this.set(s)),this},n.prototype.checkRequired=function(t,e){return u._isRef(this,t,e,!0)?!!t:t instanceof f},n.prototype.cast=function(e,n,i){if(u._isRef(this,e,n,i)){if(null===e||void 0===e)return e;if(a||(a=t("./../document")),e instanceof a)return e.$__.wasPopulated=!0,e;if(e instanceof f)return e;if(r.isBuffer(e)||!l.isObject(e))throw new c("ObjectId",e,this.path);var o=n.$__fullPath(this.path),s=n.ownerDocument?n.ownerDocument():n,h=s.populated(o,!0),p=e;return n.$__.populated&&n.$__.populated[o]&&n.$__.populated[o].options&&n.$__.populated[o].options.options&&n.$__.populated[o].options.options.lean||(p=new h.options.model(e),p.$__.wasPopulated=!0),p}if(null===e||void 0===e)return e;if(e instanceof f)return e;if(e._id){if(e._id instanceof f)return e._id;if(e._id.toString instanceof Function)try{return f.createFromHexString(e._id.toString())}catch(t){}}if(e.toString instanceof Function)try{return f.createFromHexString(e.toString())}catch(t){throw new c("ObjectId",e,this.path)}throw new c("ObjectId",e,this.path)},n.prototype.$conditionalHandlers=l.options(u.prototype.$conditionalHandlers,{$gt:i,$gte:i,$lt:i,$lte:i}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with ObjectId.");return r.call(this,e)}return this.cast(t)},e.exports=n}).call(this,t("buffer").Buffer)},{"../schematype":39,"../types/objectid":46,"../utils":48,"./../document":5,buffer:71}],37:[function(t,e,r){(function(r){function n(t){var e=this;return Array.isArray(t)?t.map(function(t){return i(e.path,t)}):r.isBuffer(t)?t:i(e.path,t)}function i(t,e){var r=Number(e);if(isNaN(r))throw new o("number",e,t);return r}var o=t("../../error/cast");e.exports=n}).call(this,t("buffer").Buffer)},{"../../error/cast":13,buffer:71}],38:[function(t,e,r){(function(r){function n(t,e){this.enumValues=[],this.regExp=null,a.call(this,t,e,"String")}function i(t){return this.castForQuery(t)}function o(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.castForQuery(t)}):[this.castForQuery(t)]}var s,a=t("../schematype"),u=a.CastError,c=t("../error").messages,f=t("../utils");n.schemaName="String",n.prototype=Object.create(a.prototype),n.prototype.constructor=n,n.prototype.enum=function(){if(this.enumValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.enumValidator},this),this.enumValidator=!1),void 0===arguments[0]||arguments[0]===!1)return this;var t,e;f.isObject(arguments[0])?(t=arguments[0].values,e=arguments[0].message):(t=arguments,e=c.String.enum);for(var r=0;r=t},message:r,type:"minlength",minlength:t})}return this},n.prototype.maxlength=function(t,e){if(this.maxlengthValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxlengthValidator},this)),null!==t&&void 0!==t){var r=e||c.String.maxlength;r=r.replace(/{MAXLENGTH}/,t),this.validators.push({validator:this.maxlengthValidator=function(e){return null===e||e.length<=t},message:r,type:"maxlength",maxlength:t})}return this},n.prototype.match=function(t,e){var r=e||c.String.match,n=function(e){if(!t)return!1;var r=null!=e&&""!==e?t.test(e):!0;return r};return this.validators.push({validator:n,message:r,type:"regexp",regexp:t}),this},n.prototype.checkRequired=function(t,e){return a._isRef(this,t,e,!0)?!!t:(t instanceof String||"string"==typeof t)&&t.length},n.prototype.cast=function(e,n,i){if(a._isRef(this,e,n,i)){if(null===e||void 0===e)return e;if(s||(s=t("./../document")),e instanceof s)return e.$__.wasPopulated=!0,e;if("string"==typeof e)return e;if(r.isBuffer(e)||!f.isObject(e))throw new u("string",e,this.path);var o=n.$__fullPath(this.path),c=n.ownerDocument?n.ownerDocument():n,l=c.populated(o,!0),h=new l.options.model(e);return h.$__.wasPopulated=!0,h}if(null===e||void 0===e)return e;if("undefined"!=typeof e){if(e._id&&"string"==typeof e._id)return e._id;if(e.toString&&e.toString!==Object.prototype.toString)return e.toString()}throw new u("string",e,this.path)},n.prototype.$conditionalHandlers=f.options(a.prototype.$conditionalHandlers,{$all:o,$gt:i,$gte:i,$lt:i,$lte:i,$options:i,$regex:i}),n.prototype.castForQuery=function(t,e){var r;if(2===arguments.length){if(r=this.$conditionalHandlers[t],!r)throw new Error("Can't use "+t+" with String.");return r.call(this,e)}return e=t,"[object RegExp]"===Object.prototype.toString.call(e)?e:this.cast(e)},e.exports=n}).call(this,t("buffer").Buffer)},{"../error":12,"../schematype":39,"../utils":48,"./../document":5,buffer:71}],39:[function(t,e,r){(function(n){function i(t,e,r){this.path=t,this.instance=r,this.validators=[],this.setters=[],this.getters=[],this.options=e,this._index=null,this.selected;for(var n in e)if(this[n]&&"function"==typeof this[n]){if("index"===n&&this._index)continue;var i=Array.isArray(e[n])?e[n]:[e[n]];this[n].apply(this,i)}}function o(t){return this.castForQuery(t)}function s(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.castForQuery(t)}):[this.castForQuery(t)]}var a=t("./utils"),u=t("./error"),c=u.messages,f=u.CastError,l=u.ValidatorError;i.prototype.default=function(t){return 1===arguments.length?(this.defaultValue="function"==typeof t?t:this.cast(t),this):(arguments.length>1&&(this.defaultValue=a.args(arguments)),this.defaultValue)},i.prototype.index=function(t){return this._index=t,a.expires(this._index),this},i.prototype.unique=function(t){return null===this._index||void 0===this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.unique=t,this},i.prototype.text=function(t){return null===this._index||void 0===this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.text=t,this},i.prototype.sparse=function(t){return null===this._index||void 0===this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.sparse=t,this},i.prototype.set=function(t){if("function"!=typeof t)throw new TypeError("A setter must be a function.");return this.setters.push(t),this},i.prototype.get=function(t){if("function"!=typeof t)throw new TypeError("A getter must be a function.");return this.getters.push(t),this},i.prototype.validate=function(t,e,r){if("function"==typeof t||t&&"RegExp"===a.getFunctionName(t.constructor)){var n;return e instanceof Object&&!r?(n=a.clone(e),n.message||(n.message=n.msg),n.validator=t,n.type=n.type||"user defined"):(e||(e=c.general.default),r||(r="user defined"),n={message:e,type:r,validator:t}),this.validators.push(n),this}var i,o,s;for(i=0,o=arguments.length;o>i;i++){if(s=arguments[i],!s||"Object"!==a.getFunctionName(s.constructor)){var u="Invalid validator. Received ("+typeof s+") "+s+". See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate";throw new Error(u)}this.validate(s.validator,s)}return this},i.prototype.required=function(t,e){if(t===!1)return this.validators=this.validators.filter(function(t){return t.validator!==this.requiredValidator},this),this.isRequired=!1,this;var r=this;this.isRequired=!0,this.requiredValidator=function(e){return"isSelected"in this&&!this.isSelected(r.path)&&!this.isModified(r.path)?!0:"function"==typeof t&&!t.apply(this)||r.checkRequired(e,this)},"string"==typeof t&&(e=t,t=void 0);var n=e||c.general.required;return this.validators.unshift({validator:this.requiredValidator,message:n,type:"required"}),this},i.prototype.getDefault=function(t,e){var r="function"==typeof this.defaultValue?this.defaultValue.call(t):this.defaultValue;return null!==r&&void 0!==r?this.cast(r,t,e):r},i.prototype.applySetters=function(t,e,r,n,i){for(var o=t,s=this.setters,a=s.length,u=this.caster;a--;)o=s[a].call(e,o,this);if(Array.isArray(o)&&u&&u.setters){for(var c=[],f=0;fr?arguments[r]:this._cast(arguments[r],arguments[0]+(r-2));t=[].splice.apply(this,e),this._registerAtomic("$set",this),this._markModified()}return t},unshift:function(){var t=[].map.call(arguments,this._cast,this);return t=this._schema.applySetters(t,this._parent),[].unshift.apply(this,t),this._registerAtomic("$set",this),this._markModified(),this.length},sort:function(){var t=[].sort.apply(this,arguments);return this._registerAtomic("$set",this),this._markModified(),t},addToSet:function(){var t=[].map.call(arguments,this._mapCast,this);t=this._schema.applySetters(t,this._parent);var e=[],r="";return t[0]instanceof o?r="doc":t[0]instanceof Date&&(r="date"),t.forEach(function(t){var n;switch(r){case"doc":n=this.some(function(e){return e.equals(t)});break;case"date":var i=+t;n=this.some(function(t){return+t===i});break;default:n=~this.indexOf(t)}n||([].push.call(this,t),this._registerAtomic("$addToSet",t),this._markModified(),[].push.call(e,t))},this),e},set:function(t,e){var r=this._cast(e,t);return r=this._schema.caster instanceof o?r:this._schema.caster.applySetters(e,this._parent),this[t]=r,this._markModified(t),this},toObject:function(t){return t&&t.depopulate?this.map(function(e){return e instanceof s?e.toObject(t):e}):this.slice()},inspect:function(){return JSON.stringify(this)},indexOf:function(t){t instanceof a&&(t=t.toString());for(var e=0,r=this.length;r>e;++e)if(t==this[e])return e;return-1}},i.mixin.remove=i.mixin.pull,e.exports=r=i}).call(this,t("buffer").Buffer)},{"../document":5,"../utils":48,"./embedded":44,"./objectid":46,buffer:71}],42:[function(t,e,r){(function(r){function n(t,e,i){var s,a=arguments.length;s=0===a||null===arguments[0]||void 0===arguments[0]?0:t;var u,c,f;Array.isArray(e)?(c=e[0],f=e[1]):u=e;var l=new r(s,u,i);return o.decorate(l,n.mixin),l.isMongooseBuffer=!0,Object.defineProperties(l,{validators:{value:[]},_path:{value:c},_parent:{value:f}}),f&&"string"==typeof c&&Object.defineProperty(l,"_schema",{value:f.schema.path(c)}),l._subtype=0,l}var i=t("../drivers").Binary,o=t("../utils");n.mixin={_parent:void 0,_subtype:void 0,_markModified:function(){var t=this._parent;return t&&t.markModified(this._path),this},write:function(){var t=r.prototype.write.apply(this,arguments);return t>0&&this._markModified(),t},copy:function(t){var e=r.prototype.copy.apply(this,arguments);return t&&t.isMongooseBuffer&&t._markModified(),e}},"writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 writeFloat writeDouble fill utf8Write binaryWrite asciiWrite set writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE writeInt16LE writeInt16BE writeInt32LE writeInt32BE writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE".split(" ").forEach(function(t){r.prototype[t]&&(n.mixin[t]=function(){var e=r.prototype[t].apply(this,arguments);return this._markModified(),e})}),n.mixin.toObject=function(t){var e="number"==typeof t?t:this._subtype||0;return new i(this,e)},n.mixin.equals=function(t){if(!r.isBuffer(t))return!1;if(this.length!==t.length)return!1;for(var e=0;ec;c++)if(n=this[c].get("_id"),null!==n&&"undefined"!=typeof n)if(n instanceof u){if(r||(r=String(t)),r==n._id)return this[c]}else if(t instanceof o||n instanceof o){if(e==n)return this[c]}else if(a.deepEqual(t,n))return this[c];return null},toObject:function(t){return this.map(function(e){return e&&e.toObject(t)||null})},inspect:function(){return Array.prototype.slice.call(this)},create:function(t){return new this._schema.casterConstructor(t)},notify:function(t){var e=this;return function(r){for(var n=e.length;n--;)if(e[n]){switch(t){case"save":r=e[n]}e[n].emit(t,r)}}}},e.exports=n}).call(this,t("buffer").Buffer)},{"../document":5,"../schema/objectid":36,"../utils":48,"./array":41,"./objectid":46,buffer:71}],44:[function(t,e,r){function n(t,e,r,n,i){e?(this.__parentArray=e,this.__parent=e._parent):(this.__parentArray=void 0,this.__parent=void 0),this.__index=i,o.call(this,t,n,r);var s=this;this.on("isNew",function(t){s.isNew=t})}function i(t){function e(){r.removeListener("save",e),r.removeListener("remove",e),t.emit("remove",t),r=t=null}var r=t.ownerDocument();r.on("save",e),r.on("remove",e)}var o=t("../document_provider")(),s=t("../promise_provider");n.prototype=Object.create(o.prototype),n.prototype.constructor=n,n.prototype.markModified=function(t){this.$__.activePaths.modify(t),this.__parentArray&&(this.isNew?this.__parentArray._markModified():this.__parentArray._markModified(this,t))},n.prototype.save=function(t){var e=s.get();return new e.ES6(function(e){t&&t(),e()})},n.prototype.remove=function(t){if(!this.__parentArray)return this;var e;if(!this.willRemove){if(e=this._doc._id,!e)throw new Error("For your own good, Mongoose does not know how to remove an EmbeddedDocument that has no _id");this.__parentArray.pull({_id:e}),this.willRemove=!0,i(this)}return t&&t(null),this},n.prototype.update=function(){throw new Error("The #update method is not available on EmbeddedDocuments")},n.prototype.inspect=function(){return this.toObject()},n.prototype.invalidate=function(t,e,r,n){if(!this.__parent){var i="Unable to invalidate a subdocument that has not been added to an array.";throw new Error(i)}var o=this.__index;if("undefined"!=typeof o){var s=this.__parentArray._path,a=[s,o,t].join(".");this.__parent.invalidate(a,e,r)}return n&&(this.$__.validationError=this.ownerDocument().$__.validationError),!0},n.prototype.$markValid=function(t){if(this.__parent){var e=this.__index;if("undefined"!=typeof e){var r=this.__parentArray._path,n=[r,e,t].join(".");this.__parent.$markValid(n)}}},n.prototype.$isValid=function(t){var e=this.__index;return"undefined"!=typeof e?!this.__parent.$__.validationError||!this.__parent.$__.validationError.errors[this.$__fullPath(t)]:!0},n.prototype.ownerDocument=function(){if(this.$__.ownerDocument)return this.$__.ownerDocument;var t=this.__parent;if(!t)return this;for(;t.__parent;)t=t.__parent;return this.$__.ownerDocument=t,this.$__.ownerDocument},n.prototype.$__fullPath=function(t){if(!this.$__.fullPath){var e=this;if(!e.__parent)return t;for(var r=[];e.__parent;)r.unshift(e.__parentArray._path),e=e.__parent;this.$__.fullPath=r.join("."),this.$__.ownerDocument||(this.$__.ownerDocument=e)}return t?this.$__.fullPath+"."+t:this.$__.fullPath},n.prototype.parent=function(){return this.__parent},n.prototype.parentArray=function(){return this.__parentArray},e.exports=n},{"../document_provider":6,"../promise_provider":25}],45:[function(t,e,r){r.Array=t("./array"),r.Buffer=t("./buffer"),r.Document=r.Embedded=t("./embedded"),r.DocumentArray=t("./documentarray"),r.ObjectId=t("./objectid"),r.Subdocument=t("./subdocument")},{"./array":41,"./buffer":42,"./documentarray":43,"./embedded":44,"./objectid":46,"./subdocument":47}],46:[function(t,e,r){var n=t("../drivers").ObjectId;e.exports=n},{"../drivers":11}],47:[function(t,e,r){function n(t,e){this.$isSingleNested=!0,o.call(this,t,e)}function i(t){function e(){r.removeListener("save",e),r.removeListener("remove",e),t.emit("remove",t),r=t=null}var r=t.ownerDocument();r.on("save",e),r.on("remove",e)}var o=t("../document"),s=t("../promise_provider");e.exports=n,n.prototype=Object.create(o.prototype),n.prototype.save=function(t){var e=s.get();return new e.ES6(function(e){t&&t(),e()})},n.prototype.$isValid=function(t){return this.$parent?this.$parent.$isValid([this.$basePath,t].join(".")):void 0},n.prototype.markModified=function(t){o.prototype.markModified.call(this,t),this.$parent&&this.$parent.markModified([this.$basePath,t].join("."))},n.prototype.$markValid=function(t){this.$parent&&this.$parent.$markValid([this.$basePath,t].join("."))},n.prototype.invalidate=function(t,e,r){if(this.$parent)this.$parent.invalidate([this.$basePath,t].join("."),e,r);else if("cast"===e.kind||"CastError"===e.name)throw e},n.prototype.ownerDocument=function(){if(this.$__.ownerDocument)return this.$__.ownerDocument;var t=this.$parent;if(!t)return this;for(;t.$parent;)t=t.$parent;return this.$__.ownerDocument=t,this.$__.ownerDocument},n.prototype.remove=function(t){this.$parent.set(this.$basePath,null),i(this),t&&t(null)}},{"../document":5,"../promise_provider":25}],48:[function(t,e,r){(function(e,n){function i(t){var e;return!~g.indexOf(t.toLowerCase())&&(e=y.filter(function(e){return t.match(e[0])}),e[0])?t.replace(e[0][0],e[0][1]):t}function o(t,e){var r,n,i,o,s,a=e&&e.retainKeyOrder,u=e&&e.minimize,c={};if(a)for(o in t)i=v(t[o],e),u&&"undefined"==typeof i||(r||(r=!0),c[o]=i);else for(n=Object.keys(t),s=n.length;s--;)o=n[s],i=v(t[o],e),u&&"undefined"==typeof i||(r||(r=!0),c[o]=i);return u?r&&c:c}function s(t,e){for(var r=[],n=0,i=t.length;i>n;n++)r.push(v(t[n],e));return r}function a(t,e,r,n,i,o){this.path=t,this.match=r,this.select=e,this.options=n,this.model=i,"object"==typeof o&&(this.populate=o),this._docs={}}var u,c,f,l=t("./types/objectid"),h=t("regexp-clone"),p=t("sliced"),d=t("mpath"),_=t("ms");r.toCollectionName=function(t,e){return e=e||{},"system.profile"===t?t:"system.indexes"===t?t:e.pluralization===!1?t:i(t.toLowerCase())},r.pluralization=[[/(m)an$/gi,"$1en"],[/(pe)rson$/gi,"$1ople"],[/(child)$/gi,"$1ren"],[/^(ox)$/gi,"$1en"],[/(ax|test)is$/gi,"$1es"],[/(octop|vir)us$/gi,"$1i"],[/(alias|status)$/gi,"$1es"],[/(bu)s$/gi,"$1ses"],[/(buffal|tomat|potat)o$/gi,"$1oes"],[/([ti])um$/gi,"$1a"],[/sis$/gi,"ses"],[/(?:([^f])fe|([lr])f)$/gi,"$1$2ves"],[/(hive)$/gi,"$1s"],[/([^aeiouy]|qu)y$/gi,"$1ies"],[/(x|ch|ss|sh)$/gi,"$1es"],[/(matr|vert|ind)ix|ex$/gi,"$1ices"],[/([m|l])ouse$/gi,"$1ice"],[/(kn|w|l)ife$/gi,"$1ives"],[/(quiz)$/gi,"$1zes"],[/s$/gi,"s"],[/([^a-z])$/,"$1"],[/$/gi,"s"]];var y=r.pluralization;r.uncountables=["advice","energy","excretion","digestion","cooperation","health","justice","labour","machinery","equipment","information","pollution","sewage","paper","money","species","series","rain","rice","fish","sheep","moose","deer","news","expertise","status","media"];var g=r.uncountables;r.deepEqual=function t(e,i){if(e===i)return!0;if(e instanceof Date&&i instanceof Date)return e.getTime()===i.getTime();if(e instanceof l&&i instanceof l)return e.toString()===i.toString();if(e instanceof RegExp&&i instanceof RegExp)return e.source===i.source&&e.ignoreCase===i.ignoreCase&&e.multiline===i.multiline&&e.global===i.global;if("object"!=typeof e&&"object"!=typeof i)return e==i;if(null===e||null===i||void 0===e||void 0===i)return!1;if(e.prototype!==i.prototype)return!1;if(e instanceof Number&&i instanceof Number)return e.valueOf()===i.valueOf();if(n.isBuffer(e))return r.buffer.areEqual(e,i);b(e)&&(e=e.toObject()),b(i)&&(i=i.toObject());try{var o,s,a=Object.keys(e),u=Object.keys(i)}catch(t){return!1}if(a.length!==u.length)return!1;for(a.sort(),u.sort(),s=a.length-1;s>=0;s--)if(a[s]!==u[s])return!1;for(s=a.length-1;s>=0;s--)if(o=a[s],!t(e[o],i[o]))return!1;return!0},r.clone=function(t,e){if(void 0===t||null===t)return t;if(Array.isArray(t))return s(t,e);if(b(t))return e&&e.json&&"function"==typeof t.toJSON?t.toJSON(e):t.toObject(e);if(t.constructor)switch(r.getFunctionName(t.constructor)){case"Object":return o(t,e);case"Date":return new t.constructor(+t);case"RegExp":return h(t)}return t instanceof l?new l(t.id):!t.constructor&&r.isObject(t)?o(t,e):t.valueOf?t.valueOf():void 0};var v=r.clone;r.options=function(t,e){var r,n=Object.keys(t),i=n.length;for(e=e||{};i--;)r=n[i],r in e||(e[r]=t[r]);return e},r.random=function(){return Math.random().toString().substr(3)},r.merge=function t(e,n){for(var i,o=Object.keys(n),s=o.length;s--;)i=o[s],"undefined"==typeof e[i]?e[i]=n[i]:r.isObject(n[i])&&t(e[i],n[i])};var m=Object.prototype.toString;r.toObject=function t(e){var n;if(r.isNullOrUndefined(e))return e;if(e instanceof f)return e.toObject();if(Array.isArray(e)){n=[];for(var i=0,o=e.length;o>i;++i)n.push(t(e[i]));return n}if(e.constructor&&"Object"===r.getFunctionName(e.constructor)||!e.constructor&&r.isObject(e)){n={};for(var s in e)n[s]=t(e[s]);return n}return e},r.isObject=function(t){return n.isBuffer(t)?!0:"[object Object]"===m.call(t)},r.args=p,r.tick=function(t){return"function"==typeof t?function(){try{t.apply(this,arguments)}catch(t){e.nextTick(function(){throw t})}}:void 0},r.isMongooseObject=function(e){return f||(f=t("./document")),c||(c=t("./types").Array),u||(u=t("./types").Buffer),e instanceof f||e&&e.isMongooseArray||e&&e.isMongooseBuffer};var b=r.isMongooseObject;r.expires=function(t){if(t&&"Object"===t.constructor.name&&"expires"in t){var e;e="string"!=typeof t.expires?t.expires:Math.round(_(t.expires)/1e3),t.expireAfterSeconds=e,delete t.expires}},a.prototype.constructor=Object,r.PopulateOptions=a,r.populate=function(t,e,n,i,o,s){if(1===arguments.length){if(t instanceof a)return[t];if(Array.isArray(t))return t.map(function(t){return r.populate(t)[0]});r.isObject(t)&&(i=t.match,o=t.options,e=t.select,n=t.model,s=t.populate,t=t.path)}else"string"!=typeof n&&"function"!=typeof n&&(o=i,i=n,n=void 0);if("string"!=typeof t)throw new TypeError("utils.populate: invalid path. Expected string. Got typeof `"+typeof t+"`");"object"==typeof s&&(s=r.populate(s));var u=[],c=t.split(" ");o=r.clone(o,{retainKeyOrder:!0});for(var f=0;fo;++o)if("number"==typeof t[o]||"string"==typeof t[o]){if(e[t[o]])continue;n.push(t[o]),e[t[o]]=!0}else if(t[o]instanceof l){if(r[t[o].toString()])continue;n.push(t[o]),r[t[o].toString()]=!0}else n.push(t[o]);return n},r.buffer={},r.buffer.areEqual=function(t,e){if(!n.isBuffer(t))return!1;if(!n.isBuffer(e))return!1;if(t.length!==e.length)return!1;for(var r=0,i=t.length;i>r;++r)if(t[r]!==e[r])return!1;return!0},r.getFunctionName=function(t){return t.name?t.name:(t.toString().trim().match(/^function\s*([^\s(]+)/)||[])[1]},r.decorate=function(t,e){for(var r in e)t[r]=e[r]},r.mergeClone=function(t,e){for(var n,i=Object.keys(e),o=i.length;o--;)if(n=i[o],"undefined"==typeof t[n])t[n]=r.clone(e[n],{retainKeyOrder:1});else if(r.isObject(e[n])){var s=e[n];b(e[n])&&!e[n].isMongooseBuffer&&(s=s.toObject({virtuals:!1})),r.mergeClone(t[n],s)}else t[n]=r.clone(e[n],{retainKeyOrder:1})},r.each=function(t,e){for(var r=0;r=0;n--)r=this.getters[n].call(e,r,this);return r},n.prototype.applySetters=function(t,e){for(var r=t,n=this.setters.length-1;n>=0;n--)r=this.setters[n].call(e,r,this);return r},e.exports=n},{}],50:[function(t,e,r){function n(t,e){return p.isUndefined(e)?""+e:!p.isNumber(e)||!isNaN(e)&&isFinite(e)?p.isFunction(e)||p.isRegExp(e)?e.toString():e:e.toString()}function i(t,e){return p.isString(t)?t.length=0;n--)if(i[n]!=o[n])return!1;for(n=i.length-1;n>=0;n--)if(r=i[n],!u(t[r],e[r]))return!1;return!0}function l(t,e){return t&&e?"[object RegExp]"==Object.prototype.toString.call(e)?e.test(t):t instanceof e?!0:e.call({},t)===!0?!0:!1:!1}function h(t,e,r,n){var i;p.isString(r)&&(n=r,r=null);try{e()}catch(t){i=t}if(n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&s(i,r,"Missing expected exception"+n),!t&&l(i,r)&&s(i,r,"Got unwanted exception"+n),t&&i&&r&&!l(i,r)||!t&&i)throw i}var p=t("util/"),d=Array.prototype.slice,_=Object.prototype.hasOwnProperty,y=e.exports=a;y.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=o(this),this.generatedMessage=!0);var e=t.stackStartFunction||s;if(Error.captureStackTrace)Error.captureStackTrace(this,e);else{var r=new Error;if(r.stack){var n=r.stack,i=e.name,a=n.indexOf("\n"+i);if(a>=0){var u=n.indexOf("\n",a+1);n=n.substring(u+1)}this.stack=n}}},p.inherits(y.AssertionError,Error),y.fail=s,y.ok=a,y.equal=function(t,e,r){t!=e&&s(t,e,r,"==",y.equal)},y.notEqual=function(t,e,r){t==e&&s(t,e,r,"!=",y.notEqual)},y.deepEqual=function(t,e,r){u(t,e)||s(t,e,r,"deepEqual",y.deepEqual)},y.notDeepEqual=function(t,e,r){u(t,e)&&s(t,e,r,"notDeepEqual",y.notDeepEqual)},y.strictEqual=function(t,e,r){t!==e&&s(t,e,r,"===",y.strictEqual)},y.notStrictEqual=function(t,e,r){t===e&&s(t,e,r,"!==",y.notStrictEqual)},y.throws=function(t,e,r){ +h.apply(this,[!0].concat(d.call(arguments)))},y.doesNotThrow=function(t,e){h.apply(this,[!1].concat(d.call(arguments)))},y.ifError=function(t){if(t)throw t};var g=Object.keys||function(t){var e=[];for(var r in t)_.call(t,r)&&e.push(r);return e}},{"util/":98}],51:[function(t,e,r){(function(t,r){!function(){function n(){}function i(t){return t}function o(t){return!!t}function s(t){return!t}function a(t){return function(){if(null===t)throw new Error("Callback was already called.");t.apply(this,arguments),t=null}}function u(t){return function(){null!==t&&(t.apply(this,arguments),t=null)}}function c(t){return L(t)||"number"==typeof t.length&&t.length>=0&&t.length%1===0}function f(t,e){for(var r=-1,n=t.length;++rn?n:null}):(r=U(t),e=r.length,function(){return n++,e>n?r[n]:null})}function g(t,e){return e=null==e?t.length-1:+e,function(){for(var r=Math.max(arguments.length-e,0),n=Array(r),i=0;r>i;i++)n[i]=arguments[i+e];switch(e){case 0:return t.call(this,n);case 1:return t.call(this,arguments[0],n)}}}function v(t){return function(e,r,n){return t(e,n)}}function m(t){return function(e,r,i){i=u(i||n),e=e||[];var o=y(e);if(0>=t)return i(null);var s=!1,c=0,f=!1;!function n(){if(s&&0>=c)return i(null);for(;t>c&&!f;){var u=o();if(null===u)return s=!0,void(0>=c&&i(null));c+=1,r(e[u],u,a(function(t){c-=1,t?(i(t),f=!0):n()}))}}()}}function b(t){return function(e,r,n){return t(R.eachOf,e,r,n)}}function w(t){return function(e,r,n,i){return t(m(r),e,n,i)}}function E(t){return function(e,r,n){return t(R.eachOfSeries,e,r,n)}}function O(t,e,r,i){i=u(i||n),e=e||[];var o=c(e)?[]:{};t(e,function(t,e,n){r(t,function(t,r){o[e]=r,n(t)})},function(t){i(t,o)})}function A(t,e,r,n){var i=[];t(e,function(t,e,n){r(t,function(r){r&&i.push({index:e,value:t}),n()})},function(){n(l(i.sort(function(t,e){return t.index-e.index}),function(t){return t.value}))})}function S(t,e,r,n){A(t,e,function(t,e){r(t,function(t){e(!t)})},n)}function j(t,e,r){return function(n,i,o,s){function a(){s&&s(r(!1,void 0))}function u(t,n,i){return s?void o(t,function(n){s&&e(n)&&(s(r(!0,t)),s=o=!1),i()}):i()}arguments.length>3?t(n,i,u,a):(s=o,o=i,t(n,u,a))}}function N(t,e){return e}function x(t,e,r){r=r||n;var i=c(e)?[]:{};t(e,function(t,e,r){t(g(function(t,n){n.length<=1&&(n=n[0]),i[e]=n,r(t)}))},function(t){r(t,i)})}function B(t,e,r,n){var i=[];t(e,function(t,e,n){r(t,function(t,e){i=i.concat(e||[]),n(t)})},function(t){n(t,i)})}function T(t,e,r){function i(t,e,r,i){if(null!=i&&"function"!=typeof i)throw new Error("task callback must be a function");return t.started=!0,L(e)||(e=[e]),0===e.length&&t.idle()?R.setImmediate(function(){t.drain()}):(f(e,function(e){var o={data:e,callback:i||n};r?t.tasks.unshift(o):t.tasks.push(o),t.tasks.length===t.concurrency&&t.saturated()}),void R.setImmediate(t.process))}function o(t,e){return function(){s-=1;var r=!1,n=arguments;f(e,function(t){f(u,function(e,n){e!==t||r||(u.splice(n,1),r=!0)}),t.callback.apply(t,n)}),t.tasks.length+s===0&&t.drain(),t.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,u=[],c={tasks:[],concurrency:e,payload:r,saturated:n,empty:n,drain:n,started:!1,paused:!1,push:function(t,e){i(c,t,!1,e)},kill:function(){c.drain=n,c.tasks=[]},unshift:function(t,e){i(c,t,!0,e)},process:function(){for(;!c.paused&&s=e;e++)R.setImmediate(c.process)}}};return c}function k(t){return g(function(e,r){e.apply(null,r.concat([g(function(e,r){"object"==typeof console&&(e?console.error&&console.error(e):console[t]&&f(r,function(e){console[t](e)}))})]))})}function $(t){return function(e,r,n){t(h(e),r,n)}}function I(t){return g(function(e,r){var n=g(function(r){var n=this,i=r.pop();return t(e,function(t,e,i){t.apply(n,r.concat([i]))},i)});return r.length?n.apply(this,r):n})}function D(t){return g(function(e){var r=e.pop();e.push(function(){var t=arguments;n?R.setImmediate(function(){r.apply(null,t)}):r.apply(null,t)});var n=!0;t.apply(this,e),n=!1})}var P,R={},C="object"==typeof self&&self.self===self&&self||"object"==typeof r&&r.global===r&&r||this;null!=C&&(P=C.async),R.noConflict=function(){return C.async=P,R};var M=Object.prototype.toString,L=Array.isArray||function(t){return"[object Array]"===M.call(t)},F=function(t){var e=typeof t;return"function"===e||"object"===e&&!!t},U=Object.keys||function(t){var e=[];for(var r in t)t.hasOwnProperty(r)&&e.push(r);return e},V="function"==typeof setImmediate&&setImmediate,q=V?function(t){V(t)}:function(t){setTimeout(t,0)};"object"==typeof t&&"function"==typeof t.nextTick?R.nextTick=t.nextTick:R.nextTick=q,R.setImmediate=V?q:R.nextTick,R.forEach=R.each=function(t,e,r){return R.eachOf(t,v(e),r)},R.forEachSeries=R.eachSeries=function(t,e,r){return R.eachOfSeries(t,v(e),r)},R.forEachLimit=R.eachLimit=function(t,e,r,n){return m(e)(t,v(r),n)},R.forEachOf=R.eachOf=function(t,e,r){function i(t){c--,t?r(t):null===o&&0>=c&&r(null)}r=u(r||n),t=t||[];for(var o,s=y(t),c=0;null!=(o=s());)c+=1,e(t[o],o,a(i));0===c&&r(null)},R.forEachOfSeries=R.eachOfSeries=function(t,e,r){function i(){var n=!0;return null===s?r(null):(e(t[s],s,a(function(t){if(t)r(t);else{if(s=o(),null===s)return r(null);n?R.setImmediate(i):i()}})),void(n=!1))}r=u(r||n),t=t||[];var o=y(t),s=o();i()},R.forEachOfLimit=R.eachOfLimit=function(t,e,r,n){m(e)(t,r,n)},R.map=b(O),R.mapSeries=E(O),R.mapLimit=w(O),R.inject=R.foldl=R.reduce=function(t,e,r,n){R.eachOfSeries(t,function(t,n,i){r(e,t,function(t,r){e=r,i(t)})},function(t){n(t,e)})},R.foldr=R.reduceRight=function(t,e,r,n){var o=l(t,i).reverse();R.reduce(o,e,r,n)},R.transform=function(t,e,r,n){3===arguments.length&&(n=r,r=e,e=L(t)?[]:{}),R.eachOf(t,function(t,n,i){r(e,t,n,i)},function(t){n(t,e)})},R.select=R.filter=b(A),R.selectLimit=R.filterLimit=w(A),R.selectSeries=R.filterSeries=E(A),R.reject=b(S),R.rejectLimit=w(S),R.rejectSeries=E(S),R.any=R.some=j(R.eachOf,o,i),R.someLimit=j(R.eachOfLimit,o,i),R.all=R.every=j(R.eachOf,s,s),R.everyLimit=j(R.eachOfLimit,s,s),R.detect=j(R.eachOf,i,N),R.detectSeries=j(R.eachOfSeries,i,N),R.detectLimit=j(R.eachOfLimit,i,N),R.sortBy=function(t,e,r){function n(t,e){var r=t.criteria,n=e.criteria;return n>r?-1:r>n?1:0}R.map(t,function(t,r){e(t,function(e,n){e?r(e):r(null,{value:t,criteria:n})})},function(t,e){return t?r(t):void r(null,l(e.sort(n),function(t){return t.value}))})},R.auto=function(t,e,r){function i(t){v.unshift(t)}function o(t){var e=_(v,t);e>=0&&v.splice(e,1)}function s(){c--,f(v.slice(0),function(t){t()})}"function"==typeof arguments[1]&&(r=e,e=null),r=u(r||n);var a=U(t),c=a.length;if(!c)return r(null);e||(e=c);var l={},h=0,y=!1,v=[];i(function(){c||r(null,l)}),f(a,function(n){function a(){return e>h&&p(m,function(t,e){return t&&l.hasOwnProperty(e)},!0)&&!l.hasOwnProperty(n)}function u(){a()&&(h++,o(u),f[f.length-1](v,l))}if(!y){for(var c,f=L(t[n])?t[n]:[t[n]],v=g(function(t,e){if(h--,e.length<=1&&(e=e[0]),t){var i={};d(l,function(t,e){i[e]=t}),i[n]=e,y=!0,r(t,i)}else l[n]=e,R.setImmediate(s)}),m=f.slice(0,f.length-1),b=m.length;b--;){if(!(c=t[m[b]]))throw new Error("Has nonexistent dependency in "+m.join(", "));if(L(c)&&_(c,n)>=0)throw new Error("Has cyclic dependencies")}a()?(h++,f[f.length-1](v,l)):i(u)}})},R.retry=function(t,e,r){function n(t,e){if("number"==typeof e)t.times=parseInt(e,10)||o;else{if("object"!=typeof e)throw new Error("Unsupported argument type for 'times': "+typeof e);t.times=parseInt(e.times,10)||o,t.interval=parseInt(e.interval,10)||s}}function i(t,e){function r(t,r){return function(n){t(function(t,e){n(!t||r,{err:t,result:e})},e)}}function n(t){return function(e){setTimeout(function(){e(null)},t)}}for(;u.times;){var i=!(u.times-=1);a.push(r(u.task,i)),!i&&u.interval>0&&a.push(n(u.interval))}R.series(a,function(e,r){r=r[r.length-1],(t||u.callback)(r.err,r.result)})}var o=5,s=0,a=[],u={times:o,interval:s},c=arguments.length;if(1>c||c>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=c&&"function"==typeof t&&(r=e,e=t),"function"!=typeof t&&n(u,t),u.callback=r,u.task=e,u.callback?i():i},R.waterfall=function(t,e){function r(t){return g(function(n,i){if(n)e.apply(null,[n].concat(i));else{var o=t.next();o?i.push(r(o)):i.push(e),D(t).apply(null,i)}})}if(e=u(e||n),!L(t)){var i=new Error("First argument to waterfall must be an array of functions");return e(i)}return t.length?void r(R.iterator(t))():e()},R.parallel=function(t,e){x(R.eachOf,t,e)},R.parallelLimit=function(t,e,r){x(m(e),t,r)},R.series=function(t,e){x(R.eachOfSeries,t,e)},R.iterator=function(t){function e(r){function n(){return t.length&&t[r].apply(null,arguments),n.next()}return n.next=function(){return rn;){var o=n+(i-n+1>>>1);r(e,t[o])>=0?n=o:i=o-1}return n}function o(t,e,o,s){if(null!=s&&"function"!=typeof s)throw new Error("task callback must be a function");return t.started=!0,L(e)||(e=[e]),0===e.length?R.setImmediate(function(){t.drain()}):void f(e,function(e){var a={data:e,priority:o,callback:"function"==typeof s?s:n};t.tasks.splice(i(t.tasks,a,r)+1,0,a),t.tasks.length===t.concurrency&&t.saturated(),R.setImmediate(t.process)})}var s=R.queue(t,e);return s.push=function(t,e,r){o(s,t,e,r)},delete s.unshift,s},R.cargo=function(t,e){return T(t,1,e)},R.log=k("log"),R.dir=k("dir"),R.memoize=function(t,e){var r={},n={},o=Object.prototype.hasOwnProperty;e=e||i;var s=g(function(i){var s=i.pop(),a=e.apply(null,i);o.call(r,a)?R.setImmediate(function(){s.apply(null,r[a])}):o.call(n,a)?n[a].push(s):(n[a]=[s],t.apply(null,i.concat([g(function(t){r[a]=t;var e=n[a];delete n[a];for(var i=0,o=e.length;o>i;i++)e[i].apply(null,t)})])))});return s.memo=r,s.unmemoized=t,s},R.unmemoize=function(t){return function(){return(t.unmemoized||t).apply(null,arguments)}},R.times=$(R.map),R.timesSeries=$(R.mapSeries),R.timesLimit=function(t,e,r,n){return R.mapLimit(h(t),e,r,n)},R.seq=function(){var t=arguments;return g(function(e){var r=this,i=e[e.length-1];"function"==typeof i?e.pop():i=n,R.reduce(t,e,function(t,e,n){e.apply(r,t.concat([g(function(t,e){n(t,e)})]))},function(t,e){i.apply(r,[t].concat(e))})})},R.compose=function(){return R.seq.apply(null,Array.prototype.reverse.call(arguments))},R.applyEach=I(R.eachOf),R.applyEachSeries=I(R.eachOfSeries),R.forever=function(t,e){function r(t){return t?i(t):void o(r)}var i=a(e||n),o=D(t);r()},R.ensureAsync=D,R.constant=g(function(t){var e=[null].concat(t);return function(t){return t.apply(this,e)}}),R.wrapSync=R.asyncify=function(t){return g(function(e){var r,n=e.pop();try{r=t.apply(this,e)}catch(t){return n(t)}F(r)&&"function"==typeof r.then?r.then(function(t){n(null,t)}).catch(function(t){n(t.message?t:new Error(t))}):n(null,r)})},"object"==typeof e&&e.exports?e.exports=R:"function"==typeof define&&define.amd?define([],function(){return R}):C.async=R}()}).call(this,t("g5I+bs"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"g5I+bs":94}],52:[function(t,e,r){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(t){"use strict";function e(t){var e=t.charCodeAt(0);return e===s?62:e===a?63:u>e?-1:u+10>e?e-u+26+26:f+26>e?e-f:c+26>e?e-c+26:void 0}function r(t){function r(t){c[l++]=t}var n,i,s,a,u,c;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var f=t.length;u="="===t.charAt(f-2)?2:"="===t.charAt(f-1)?1:0,c=new o(3*t.length/4-u),s=u>0?t.length-4:t.length;var l=0;for(n=0,i=0;s>n;n+=4,i+=3)a=e(t.charAt(n))<<18|e(t.charAt(n+1))<<12|e(t.charAt(n+2))<<6|e(t.charAt(n+3)),r((16711680&a)>>16),r((65280&a)>>8),r(255&a);return 2===u?(a=e(t.charAt(n))<<2|e(t.charAt(n+1))>>4,r(255&a)):1===u&&(a=e(t.charAt(n))<<10|e(t.charAt(n+1))<<4|e(t.charAt(n+2))>>2,r(a>>8&255),r(255&a)),c}function i(t){function e(t){return n.charAt(t)}function r(t){return e(t>>18&63)+e(t>>12&63)+e(t>>6&63)+e(63&t)}var i,o,s,a=t.length%3,u="";for(i=0,s=t.length-a;s>i;i+=3)o=(t[i]<<16)+(t[i+1]<<8)+t[i+2],u+=r(o);switch(a){case 1:o=t[t.length-1],u+=e(o>>2),u+=e(o<<4&63),u+="==";break;case 2:o=(t[t.length-2]<<8)+t[t.length-1],u+=e(o>>10),u+=e(o>>4&63),u+=e(o<<2&63),u+="="}return u}var o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="+".charCodeAt(0),a="/".charCodeAt(0),u="0".charCodeAt(0),c="a".charCodeAt(0),f="A".charCodeAt(0);t.toByteArray=r,t.fromByteArray=i}("undefined"==typeof r?this.base64js={}:r)},{}],53:[function(t,e,r){(function(r){function n(t,e){if(!(this instanceof n))return new n(t,e);if(this._bsontype="Binary",t instanceof Number?(this.sub_type=t,this.position=0):(this.sub_type=null==e?o:e,this.position=0),null==t||t instanceof Number)"undefined"!=typeof i?this.buffer=new i(n.BUFFER_SIZE):"undefined"!=typeof Uint8Array?this.buffer=new Uint8Array(new ArrayBuffer(n.BUFFER_SIZE)):this.buffer=new Array(n.BUFFER_SIZE),this.position=0;else{if("string"==typeof t)if("undefined"!=typeof i)this.buffer=new i(t);else{if("undefined"==typeof Uint8Array&&"[object Array]"!=Object.prototype.toString.call(t))throw new Error("only String, Buffer, Uint8Array or Array accepted");this.buffer=s(t)}else this.buffer=t;this.position=t.length}}if("undefined"!=typeof r)var i=t("buffer").Buffer;n.prototype.put=function(t){if(null!=t.length&&"number"!=typeof t&&1!=t.length)throw new Error("only accepts single character String, Uint8Array or Array");if("number"!=typeof t&&0>t||t>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var e=null;if(e="string"==typeof t?t.charCodeAt(0):null!=t.length?t[0]:t,this.buffer.length>this.position)this.buffer[this.position++]=e;else if("undefined"!=typeof i&&i.isBuffer(this.buffer)){var r=new i(n.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length),this.buffer=r,this.buffer[this.position++]=e}else{var r=null;r="[object Uint8Array]"==Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(n.BUFFER_SIZE+this.buffer.length)):new Array(n.BUFFER_SIZE+this.buffer.length);for(var o=0;othis.position?e+t.length:this.position;else if("undefined"!=typeof i&&"string"==typeof t&&i.isBuffer(this.buffer))this.buffer.write(t,e,"binary"),this.position=e+t.length>this.position?e+t.length:this.position;else if("[object Uint8Array]"==Object.prototype.toString.call(t)||"[object Array]"==Object.prototype.toString.call(t)&&"string"!=typeof t){for(var n=0;nthis.position?e:this.position}else if("string"==typeof t){for(var n=0;nthis.position?e:this.position}},n.prototype.read=function(t,e){if(e=e&&e>0?e:this.position,this.buffer.slice)return this.buffer.slice(t,t+e);for(var r="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e)):new Array(e),n=0;e>n;n++)r[n]=this.buffer[t++];return r},n.prototype.value=function(t){if(t=null==t?!1:t,t&&"undefined"!=typeof i&&i.isBuffer(this.buffer)&&this.buffer.length==this.position)return this.buffer;if("undefined"!=typeof i&&i.isBuffer(this.buffer))return t?this.buffer.slice(0,this.position):this.buffer.toString("binary",0,this.position);if(t){if(null!=this.buffer.slice)return this.buffer.slice(0,this.position);for(var e="[object Uint8Array]"==Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(this.position)):new Array(this.position),r=0;ri;i++)n+=String.fromCharCode(t[i]);return n};n.BUFFER_SIZE=256,n.SUBTYPE_DEFAULT=0,n.SUBTYPE_FUNCTION=1,n.SUBTYPE_BYTE_ARRAY=2,n.SUBTYPE_UUID_OLD=3,n.SUBTYPE_UUID=4,n.SUBTYPE_MD5=5,n.SUBTYPE_USER_DEFINED=128,e.exports=n,e.exports.Binary=n}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:71}],54:[function(t,e,n){(function(e){function i(t,e){return this instanceof i?(this.bigEndian=t,void(this.allowExceptions=e)):new i(t,e)}function o(t,e){this.bigEndian=t||0,this.buffer=[],this.setBuffer(e)}for(var s=String.fromCharCode,a=[],u=0;64>u;u++)a[u]=Math.pow(2,u);i.warn=function(t){if(this.allowExceptions)throw new Error(t);return 1},i.decodeFloat=function(t,e,r){var n=new this.Buffer(this.bigEndian,t);n.checkBuffer(e+r+1);var i=a[r-1]-1,o=n.readBits(e+r,1),s=n.readBits(e,r),u=0,c=2,f=n.buffer.length+(-e>>3)-1;do for(var l=n.buffer[++f],h=e%8||8,p=1<>=1;l&p&&(u+=1/c),c*=2);while(e-=h);return s==(i<<1)+1?u?NaN:o?-(1/0):+(1/0):(1+-2*o)*(s||u?s?Math.pow(2,s-i)*(1+u):Math.pow(2,-i+1)*u:0)},i.decodeInt=function(t,e,r,n){var i=new this.Buffer(this.bigEndian||n,t),o=i.readBits(0,e),s=a[e];return r&&o>=s/2?o-s:o},i.encodeFloat=function(t,e,n){var i,o,s,u,c,f=a[n-1]-1,l=-f+1,h=f,p=l-e,d=parseFloat(t),_=isNaN(d)||d==-(1/0)||d==+(1/0)?d:0,y=0,g=2*f+1+e+3,v=new Array(g),m=(d=0!==_?0:d)<0,b=Math.floor(d=Math.abs(d)),w=d-b;for(u=g;u;v[--u]=0);for(u=f+2;b&&u;v[--u]=b%2,b=Math.floor(b/2));for(u=f+1;w>0&&u;(v[++u]=((w*=2)>=1)-0)&&--w);for(u=-1;++u=l&&h>=y?u+1:f+1-(y=l-1)))+1]){if(!(o=v[i]))for(c=i+2;!o&&g>c;o=v[c++]);for(c=i+1;o&&--c>=0;(v[c]=!v[c]-0)&&(o=0));}for(u=0>u-2?-1:u-3;++u=l&&h>=y?++u:l>y&&(y!=f+1-g&&p>y&&this.warn("encodeFloat::float underflow"),u=f+1-(y=l-1)),(b||0!==_)&&(this.warn(b?"encodeFloat::float overflow":"encodeFloat::"+_),y=h+1,u=f+2,_==-(1/0)?m=1:isNaN(_)&&(v[u]=1)),d=Math.abs(y+f),c=n+1,s="";--c;s=d%2+s,d=d>>=1);for(d=0,c=0,u=(s=(m?"1":"0")+s+v.slice(u,u+e).join("")).length,r=[];u;c=(c+1)%8)d+=(1<=i||-(i/2)>t)&&(this.warn("encodeInt::overflow"),t=0),0>t&&(t+=i);for(var o=[];t;o[o.length]=String.fromCharCode(t%256),t=Math.floor(t/256));for(e=-(-e>>3)-o.length;e--;o[o.length]="\x00");return(this.bigEndian||n?o.reverse():o).join("")},i.toSmall=function(t){return this.decodeInt(t,8,!0)},i.fromSmall=function(t){return this.encodeInt(t,8,!0)},i.toByte=function(t){return this.decodeInt(t,8,!1)},i.fromByte=function(t){return this.encodeInt(t,8,!1)},i.toShort=function(t){return this.decodeInt(t,16,!0)},i.fromShort=function(t){return this.encodeInt(t,16,!0)},i.toWord=function(t){return this.decodeInt(t,16,!1)},i.fromWord=function(t){return this.encodeInt(t,16,!1)},i.toInt=function(t){return this.decodeInt(t,32,!0)},i.fromInt=function(t){return this.encodeInt(t,32,!0)},i.toLong=function(t){return this.decodeInt(t,64,!0)},i.fromLong=function(t){return this.encodeInt(t,64,!0)},i.toDWord=function(t){return this.decodeInt(t,32,!1)},i.fromDWord=function(t){return this.encodeInt(t,32,!1)},i.toQWord=function(t){return this.decodeInt(t,64,!0)},i.fromQWord=function(t){return this.encodeInt(t,64,!0)},i.toFloat=function(t){return this.decodeFloat(t,23,8)},i.fromFloat=function(t){return this.encodeFloat(t,23,8)},i.toDouble=function(t){return this.decodeFloat(t,52,11)},i.fromDouble=function(t){return this.encodeFloat(t,52,11)},i.encode_int32=function(t,e){var r,n,i,o,a;return a=0>t?t+4294967296:t,r=Math.floor(a/16777215),a&=16777215,n=Math.floor(a/65535),a&=65535,i=Math.floor(a/255),a&=255,o=Math.floor(a),e?[s(r),s(n),s(i),s(o)]:s(r)+s(n)+s(i)+s(o)},i.encode_int64=function(t){var e,r,n,i,o,a,u,c,f;return f=0>t?t+0x10000000000000000:t,e=Math.floor(f/72057594037927940),f&=72057594037927940,r=Math.floor(f/0xffffffffffff),f&=0xffffffffffff,n=Math.floor(f/0xffffffffff),f&=0xffffffffff,i=Math.floor(f/4294967295),f&=4294967295,o=Math.floor(f/16777215),f&=16777215,a=Math.floor(f/65535),f&=65535,u=Math.floor(f/255),f&=255,c=Math.floor(f),s(e)+s(r)+s(n)+s(i)+s(o)+s(a)+s(u)+s(c)},i.decode_utf8=function(t){for(var e,r=t.length,n="",i=0,o=0,s=0;r>i;)o=t.charCodeAt(i),128>o?(n+=String.fromCharCode(o),i++):o>191&&224>o?(s=t.charCodeAt(i+1),n+=String.fromCharCode((31&o)<<6|63&s),i+=2):(s=t.charCodeAt(i+1),e=t.charCodeAt(i+2),n+=String.fromCharCode((15&o)<<12|(63&s)<<6|63&e),i+=3);return n},i.encode_cstring=function(t){return unescape(encodeURIComponent(t))+i.fromByte(0)},i.encode_utf8=function(t){for(var e,r="",n=0,i=t.length;i>n;n++)e=t.charCodeAt(n),128>e?r+=String.fromCharCode(e):e>127&&2048>e?(r+=String.fromCharCode(e>>6|192),r+=String.fromCharCode(63&e|128)):(r+=String.fromCharCode(e>>12|224),r+=String.fromCharCode(e>>6&63|128),r+=String.fromCharCode(63&e|128));return r},i.hprint=function(t){for(var r,n=0,i=t.length;i>n;n++)t.charCodeAt(n)<32?(r=t.charCodeAt(n)<=15?"0"+t.charCodeAt(n).toString(16):t.charCodeAt(n).toString(16),e.stdout.write(r+" ")):(r=t.charCodeAt(n)<=15?"0"+t.charCodeAt(n).toString(16):t.charCodeAt(n).toString(16),e.stdout.write(r+" "));e.stdout.write("\n\n")},i.ilprint=function(e){for(var r,n=0,i=e.length;i>n;n++)e.charCodeAt(n)<32?(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(10):e.charCodeAt(n).toString(10),t("util").debug(r+" : ")):(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(10):e.charCodeAt(n).toString(10),t("util").debug(r+" : "+e.charAt(n)))},i.hlprint=function(e){for(var r,n=0,i=e.length;i>n;n++)e.charCodeAt(n)<32?(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(16):e.charCodeAt(n).toString(16),t("util").debug(r+" : ")):(r=e.charCodeAt(n)<=15?"0"+e.charCodeAt(n).toString(16):e.charCodeAt(n).toString(16),t("util").debug(r+" : "+e.charAt(n)))},o.prototype.setBuffer=function(t){var e,r,n;if(t){for(r=e=t.length,n=this.buffer=new Array(e);r;n[e-r]=t.charCodeAt(--r));this.bigEndian&&n.reverse()}},o.prototype.hasNeededBits=function(t){return this.buffer.length>=-(-t>>3)},o.prototype.checkBuffer=function(t){if(!this.hasNeededBits(t))throw new Error("checkBuffer::missing bytes")},o.prototype.readBits=function(t,e){function r(t,e){for(;e--;t=1073741824==(1073741824&(t%=2147483648))?2*t:2*(t-1073741824)+2147483647+1);return t}if(0>t||0>=e)return 0;this.checkBuffer(t+e);for(var n,i=t%8,o=this.buffer.length-(t>>3)-1,s=this.buffer.length+(-(t+e)>>3),a=o-s,u=(this.buffer[o]>>i&(1<<(a?8-i:e))-1)+(a&&(n=(t+e)%8)?(this.buffer[s++]&(1<a;a++){var u=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;o.index=s,n[i+a]=this.deserialize(t,o),s+=u}return s},b.BSON_INT32_MAX=2147483647,b.BSON_INT32_MIN=-2147483648,b.BSON_INT64_MAX=Math.pow(2,63)-1,b.BSON_INT64_MIN=-Math.pow(2,63),b.JS_INT_MAX=9007199254740992,b.JS_INT_MIN=-9007199254740992;i.fromNumber(9007199254740992),i.fromNumber(-9007199254740992);b.BSON_DATA_NUMBER=1,b.BSON_DATA_STRING=2,b.BSON_DATA_OBJECT=3,b.BSON_DATA_ARRAY=4,b.BSON_DATA_BINARY=5,b.BSON_DATA_OID=7,b.BSON_DATA_BOOLEAN=8,b.BSON_DATA_DATE=9,b.BSON_DATA_NULL=10,b.BSON_DATA_REGEXP=11,b.BSON_DATA_CODE=13,b.BSON_DATA_SYMBOL=14,b.BSON_DATA_CODE_W_SCOPE=15,b.BSON_DATA_INT=16,b.BSON_DATA_TIMESTAMP=17,b.BSON_DATA_LONG=18,b.BSON_DATA_MIN_KEY=255,b.BSON_DATA_MAX_KEY=127,b.BSON_BINARY_SUBTYPE_DEFAULT=0,b.BSON_BINARY_SUBTYPE_FUNCTION=1,b.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,b.BSON_BINARY_SUBTYPE_UUID=3,b.BSON_BINARY_SUBTYPE_MD5=4,b.BSON_BINARY_SUBTYPE_USER_DEFINED=128,e.exports=b,e.exports.Code=f,e.exports.Map=n,e.exports.Symbol=c,e.exports.BSON=b,e.exports.DBRef=p,e.exports.Binary=d,e.exports.ObjectID=a,e.exports.Long=i,e.exports.Timestamp=s,e.exports.Double=o,e.exports.MinKey=l,e.exports.MaxKey=h,e.exports.BSONRegExp=u}).call(this,t("buffer").Buffer)},{"./binary":53,"./code":56,"./db_ref":57,"./double":58,"./float_parser":59,"./long":60,"./map":61,"./max_key":62,"./min_key":63,"./objectid":64,"./parser/calculate_size":65,"./parser/deserializer":66,"./parser/serializer":67,"./regexp":68,"./symbol":69,"./timestamp":70,buffer:71}],56:[function(t,e,r){var n=function t(e,r){return this instanceof t?(this._bsontype="Code",this.code=e,void(this.scope=null==r?{}:r)):new t(e,r)};n.prototype.toJSON=function(){return{scope:this.scope,code:this.code}},e.exports=n,e.exports.Code=n},{}],57:[function(t,e,r){function n(t,e,r){return this instanceof n?(this._bsontype="DBRef",this.namespace=t,this.oid=e,void(this.db=r)):new n(t,e,r)}n.prototype.toJSON=function(){return{$ref:this.namespace,$id:this.oid,$db:null==this.db?"":this.db}},e.exports=n,e.exports.DBRef=n},{}],58:[function(t,e,r){function n(t){return this instanceof n?(this._bsontype="Double",void(this.value=t)):new n(t)}n.prototype.valueOf=function(){return this.value},n.prototype.toJSON=function(){return this.value},e.exports=n,e.exports.Double=n},{}],59:[function(t,e,r){var n=function(t,e,r,n,i){var o,s,a="big"===r,u=8*i-n-1,c=(1<>1,l=-7,h=a?0:i-1,p=a?1:-1,d=t[e+h];for(h+=p,o=d&(1<<-l)-1,d>>=-l,l+=u;l>0;o=256*o+t[e+h],h+=p,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+t[e+h],h+=p,l-=8);if(0===o)o=1-f;else{if(o===c)return s?NaN:(d?-1:1)*(1/0);s+=Math.pow(2,n),o-=f}return(d?-1:1)*s*Math.pow(2,o-n)},i=function(t,e,r,n,i,o){var s,a,u,c="big"===n,f=8*o-i-1,l=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=c?o-1:0,_=c?-1:1,y=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),e+=s+h>=1?p/u:p*Math.pow(2,1-h),e*u>=2&&(s++,u/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(e*u-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[r+d]=255&a,d+=_,a/=256,i-=8);for(s=s<0;t[r+d]=255&s,d+=_,s/=256,f-=8);t[r+d-_]|=128*y};r.readIEEE754=n,r.writeIEEE754=i},{}],60:[function(t,e,r){function n(t,e){return this instanceof n?(this._bsontype="Long",this.low_=0|t,void(this.high_=0|e)):new n(t,e)}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(t){var e=t||10;if(2>e||e>36)throw Error("radix out of range: "+e);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(e),i=this.div(r),o=i.multiply(r).subtract(this);return i.toString(e)+o.toInt().toString(e)}return"-"+this.negate().toString(e)}for(var s=n.fromNumber(Math.pow(e,6)),o=this,a="";;){var u=o.div(s),c=o.subtract(u.multiply(s)).toInt(),f=c.toString(e);if(o=u,o.isZero())return f+a;for(;f.length<6;)f="0"+f;a=""+f+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!=this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},n.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},n.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(t){var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,f=0,l=0,h=0,p=0;return p+=o+c,h+=p>>>16,p&=65535,h+=i+u,l+=h>>>16,h&=65535,l+=r+a,f+=l>>>16,l&=65535,f+=e+s,f&=65535,n.fromBits(h<<16|p,f<<16|l)},n.prototype.subtract=function(t){return this.add(t.negate())},n.prototype.multiply=function(t){if(this.isZero())return n.ZERO;if(t.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return t.isOdd()?n.MIN_VALUE:n.ZERO;if(t.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate(); +if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&t.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,f=0,l=0,h=0,p=0;return p+=o*c,h+=p>>>16,p&=65535,h+=i*c,l+=h>>>16,h&=65535,h+=o*u,l+=h>>>16,h&=65535,l+=r*c,f+=l>>>16,l&=65535,l+=i*u,f+=l>>>16,l&=65535,l+=o*a,f+=l>>>16,l&=65535,f+=e*c+r*u+i*a+o*s,f&=65535,n.fromBits(h<<16|p,f<<16|l)},n.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(t.equals(n.ONE)||t.equals(n.NEG_ONE))return n.MIN_VALUE;if(t.equals(n.MIN_VALUE))return n.ONE;var e=this.shiftRight(1),r=e.div(t).shiftLeft(1);if(r.equals(n.ZERO))return t.isNegative()?n.ONE:n.NEG_ONE;var i=this.subtract(t.multiply(r)),o=r.add(i.div(t));return o}if(t.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();for(var s=n.ZERO,i=this;i.greaterThanOrEqual(t);){for(var r=Math.max(1,Math.floor(i.toNumber()/t.toNumber())),a=Math.ceil(Math.log(r)/Math.LN2),u=48>=a?1:Math.pow(2,a-48),c=n.fromNumber(r),f=c.multiply(t);f.isNegative()||f.greaterThan(i);)r-=u,c=n.fromNumber(r),f=c.multiply(t);c.isZero()&&(c=n.ONE),s=s.add(c),i=i.subtract(f)}return s},n.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(t){return n.fromBits(this.low_&t.low_,this.high_&t.high_)},n.prototype.or=function(t){return n.fromBits(this.low_|t.low_,this.high_|t.high_)},n.prototype.xor=function(t){return n.fromBits(this.low_^t.low_,this.high_^t.high_)},n.prototype.shiftLeft=function(t){if(t&=63,0==t)return this;var e=this.low_;if(32>t){var r=this.high_;return n.fromBits(e<>>32-t)}return n.fromBits(0,e<t){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>t)}return n.fromBits(e>>t-32,e>=0?0:-1)},n.prototype.shiftRightUnsigned=function(t){if(t&=63,0==t)return this;var e=this.high_;if(32>t){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>>t)}return 32==t?n.fromBits(e,0):n.fromBits(e>>>t-32,0)},n.fromInt=function(t){if(t>=-128&&128>t){var e=n.INT_CACHE_[t];if(e)return e}var r=new n(0|t,0>t?-1:0);return t>=-128&&128>t&&(n.INT_CACHE_[t]=r),r},n.fromNumber=function(t){return isNaN(t)||!isFinite(t)?n.ZERO:t<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:t+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:0>t?n.fromNumber(-t).negate():new n(t%n.TWO_PWR_32_DBL_|0,t/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(t,e){return new n(t,e)},n.fromString=function(t,e){if(0==t.length)throw Error("number format error: empty string");var r=e||10;if(2>r||r>36)throw Error("radix out of range: "+r);if("-"==t.charAt(0))return n.fromString(t.substring(1),r).negate();if(t.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+t);for(var i=n.fromNumber(Math.pow(r,8)),o=n.ZERO,s=0;sa){var c=n.fromNumber(Math.pow(r,a));o=o.multiply(c).add(n.fromNumber(u))}else o=o.multiply(i),o=o.add(n.fromNumber(u))}return o},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Long=n},{}],61:[function(t,e,r){(function(t){"use strict";if("undefined"!=typeof t.Map)e.exports=t.Map,e.exports.Map=t.Map;else{var r=function(t){this._keys=[],this._values={};for(var e=0;eu;u++)a[u]=(15>=u?"0":"")+u.toString(16);s.prototype.toHexString=function(){if(s.cacheHexString&&this.__id)return this.__id;for(var t="",e=0;e24)throw new Error("Id cannot be longer than 12 bytes");for(var r,i,o="",a=0;e>a;a+=2)r=t.substr(a,2),i=parseInt(r,16),o+=n.fromByte(i);return new s(o,t)},s.isValid=function(t){return null==t?!1:"number"==typeof t?!0:"string"==typeof t?12==t.length||24==t.length&&o.test(t):t instanceof s?!0:t.toHexString?12==t.id.length||24==t.id.length&&o.test(t.id):!1},Object.defineProperty(s.prototype,"generationTime",{enumerable:!0,get:function(){return Math.floor(n.decodeInt(this.id.substring(0,4),32,!0,!0))},set:function(t){var t=n.encodeInt(t,32,!0,!0);this.id=t+this.id.substr(4),this.toHexString()}}),e.exports=s,e.exports.ObjectID=s,e.exports.ObjectId=s}).call(this,t("g5I+bs"))},{"./binary_parser":54,"g5I+bs":94}],65:[function(t,e,r){(function(r){"use strict";function n(t,e,n,v,m){switch(e&&e.toBSON&&(e=e.toBSON()),typeof e){case"string":return 1+r.byteLength(t,"utf8")+1+4+r.byteLength(e,"utf8")+1;case"number":return Math.floor(e)===e&&e>=g.JS_INT_MIN&&e<=g.JS_INT_MAX&&e>=g.BSON_INT32_MIN&&e<=g.BSON_INT32_MAX?(null!=t?r.byteLength(t,"utf8")+1:0)+5:(null!=t?r.byteLength(t,"utf8")+1:0)+9;case"undefined":return v||!m?(null!=t?r.byteLength(t,"utf8")+1:0)+1:0;case"boolean":return(null!=t?r.byteLength(t,"utf8")+1:0)+2;case"object":if(null==e||e instanceof l||e instanceof h||"MinKey"==e._bsontype||"MaxKey"==e._bsontype)return(null!=t?r.byteLength(t,"utf8")+1:0)+1;if(e instanceof a||"ObjectID"==e._bsontype)return(null!=t?r.byteLength(t,"utf8")+1:0)+13;if(e instanceof Date||_(e))return(null!=t?r.byteLength(t,"utf8")+1:0)+9;if("undefined"!=typeof r&&r.isBuffer(e))return(null!=t?r.byteLength(t,"utf8")+1:0)+6+e.length;if(e instanceof i||e instanceof o||e instanceof s||"Long"==e._bsontype||"Double"==e._bsontype||"Timestamp"==e._bsontype)return(null!=t?r.byteLength(t,"utf8")+1:0)+9;if(e instanceof f||"Code"==e._bsontype)return null!=e.scope&&Object.keys(e.scope).length>0?(null!=t?r.byteLength(t,"utf8")+1:0)+1+4+4+r.byteLength(e.code.toString(),"utf8")+1+y(e.scope,n,m):(null!=t?r.byteLength(t,"utf8")+1:0)+1+4+r.byteLength(e.code.toString(),"utf8")+1;if(e instanceof d||"Binary"==e._bsontype)return e.sub_type==d.SUBTYPE_BYTE_ARRAY?(null!=t?r.byteLength(t,"utf8")+1:0)+(e.position+1+4+1+4):(null!=t?r.byteLength(t,"utf8")+1:0)+(e.position+1+4+1);if(e instanceof u||"Symbol"==e._bsontype)return(null!=t?r.byteLength(t,"utf8")+1:0)+r.byteLength(e.value,"utf8")+4+1+1;if(e instanceof p||"DBRef"==e._bsontype){var b={$ref:e.namespace,$id:e.oid};return null!=e.db&&(b.$db=e.db),(null!=t?r.byteLength(t,"utf8")+1:0)+1+y(b,n,m)}return e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)?(null!=t?r.byteLength(t,"utf8")+1:0)+1+r.byteLength(e.source,"utf8")+1+(e.global?1:0)+(e.ignoreCase?1:0)+(e.multiline?1:0)+1:e instanceof c||"BSONRegExp"==e._bsontype?(null!=t?r.byteLength(t,"utf8")+1:0)+1+r.byteLength(e.pattern,"utf8")+1+r.byteLength(e.options,"utf8")+1:(null!=t?r.byteLength(t,"utf8")+1:0)+y(e,n,m)+1;case"function":if(e instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(e)||"[object RegExp]"==String.call(e))return(null!=t?r.byteLength(t,"utf8")+1:0)+1+r.byteLength(e.source,"utf8")+1+(e.global?1:0)+(e.ignoreCase?1:0)+(e.multiline?1:0)+1;if(n&&null!=e.scope&&Object.keys(e.scope).length>0)return(null!=t?r.byteLength(t,"utf8")+1:0)+1+4+4+r.byteLength(e.toString(),"utf8")+1+y(e.scope,n,m);if(n)return(null!=t?r.byteLength(t,"utf8")+1:0)+1+4+r.byteLength(e.toString(),"utf8")+1}return 0}var i=(t("../float_parser").writeIEEE754,t("../float_parser").readIEEE754,t("../long").Long),o=t("../double").Double,s=t("../timestamp").Timestamp,a=t("../objectid").ObjectID,u=t("../symbol").Symbol,c=t("../regexp").BSONRegExp,f=t("../code").Code,l=t("../min_key").MinKey,h=t("../max_key").MaxKey,p=t("../db_ref").DBRef,d=t("../binary").Binary,_=function(t){return"object"==typeof t&&"[object Date]"===Object.prototype.toString.call(t)},y=function(t,e,r){var i=5;if(Array.isArray(t))for(var o=0;oi||t.lengthh||h>t.length)throw new Error("corrupt bson message");for(var p=n?[]:{};;){var d=t[e++];if(0==d)break;for(var _=e;0!==t[_]&&_=t.length)throw new Error("Bad BSON Document: illegal CString");var y=t.toString("utf8",e,_);if(e=_+1,d==BSON.BSON_DATA_STRING){var g=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;if(0>=g||g>t.length-e||0!=t[e+g-1])throw new Error("bad string length in bson");p[y]=t.toString("utf8",e,e+g-1),e+=g}else if(d==BSON.BSON_DATA_OID){var v=t.toString("binary",e,e+12);p[y]=new ObjectID(v),e+=12}else if(d==BSON.BSON_DATA_INT)p[y]=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;else if(d==BSON.BSON_DATA_NUMBER)p[y]=t.readDoubleLE(e),e+=8;else if(d==BSON.BSON_DATA_DATE){var m=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,b=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;p[y]=new Date(new Long(m,b).toNumber())}else if(d==BSON.BSON_DATA_BOOLEAN)p[y]=1==t[e++];else if(d==BSON.BSON_DATA_OBJECT){var w=e,E=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;if(0>=E||E>t.length-e)throw new Error("bad embedded document length in bson");c?p[y]=t.slice(e,e+E):p[y]=deserializeObject(t,w,r,!1),e+=E}else if(d==BSON.BSON_DATA_ARRAY){var w=e,E=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24,O=r;if(u&&u[y]){O={};for(var A in r)O[A]=r[A];O.raw=!0}p[y]=deserializeObject(t,w,O,!0),e+=E}else if(d==BSON.BSON_DATA_UNDEFINED||d==BSON.BSON_DATA_NULL)p[y]=null;else if(d==BSON.BSON_DATA_LONG){var m=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,b=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,S=new Long(m,b);a?p[y]=S.lessThanOrEqual(JS_INT_MAX_LONG)&&S.greaterThanOrEqual(JS_INT_MIN_LONG)?S.toNumber():S:p[y]=S}else if(d==BSON.BSON_DATA_BINARY){var j=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,N=t[e++];if(null!=t.slice)N==Binary.SUBTYPE_BYTE_ARRAY&&(j=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24),l?p[y]=t.slice(e,e+j):p[y]=new Binary(t.slice(e,e+j),N);else{var x="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(j)):new Array(j);N==Binary.SUBTYPE_BYTE_ARRAY&&(j=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24);for(var _=0;j>_;_++)x[_]=t[e+_];l?p[y]=x:p[y]=new Binary(x,N)}e+=j}else if(d==BSON.BSON_DATA_REGEXP&&0==f){for(var _=e;0!==t[_]&&_=t.length)throw new Error("Bad BSON Document: illegal CString");var B=t.toString("utf8",e,_);e=_+1;for(var _=e;0!==t[_]&&_=t.length)throw new Error("Bad BSON Document: illegal CString");var T=t.toString("utf8",e,_);e=_+1;for(var k=new Array(T.length),_=0;_=t.length)throw new Error("Bad BSON Document: illegal CString");var B=t.toString("utf8",e,_);e=_+1;for(var _=e;0!==t[_]&&_=t.length)throw new Error("Bad BSON Document: illegal CString");var T=t.toString("utf8",e,_);e=_+1,p[y]=new BSONRegExp(B,T)}else if(d==BSON.BSON_DATA_SYMBOL){var g=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;if(0>=g||g>t.length-e||0!=t[e+g-1])throw new Error("bad string length in bson");p[y]=new Symbol(t.toString("utf8",e,e+g-1)),e+=g}else if(d==BSON.BSON_DATA_TIMESTAMP){var m=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,b=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;p[y]=new Timestamp(m,b)}else if(d==BSON.BSON_DATA_MIN_KEY)p[y]=new MinKey;else if(d==BSON.BSON_DATA_MAX_KEY)p[y]=new MaxKey;else if(d==BSON.BSON_DATA_CODE){var g=t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24;if(0>=g||g>t.length-e||0!=t[e+g-1])throw new Error("bad string length in bson");var $=t.toString("utf8",e,e+g-1);if(i){if(o){var I=s?crc32($):$;p[y]=isolateEvalWithHash(functionCache,I,$,p)}else p[y]=isolateEval($)}else p[y]=new Code($,{});e+=g}else if(d==BSON.BSON_DATA_CODE_W_SCOPE){var g=(t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24,t[e++]|t[e++]<<8|t[e++]<<16|t[e++]<<24);if(0>=g||g>t.length-e||0!=t[e+g-1])throw new Error("bad string length in bson");var $=t.toString("utf8",e,e+g-1);e+=g;var w=e,E=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24,D=deserializeObject(t,w,r,!1);if(e+=E,i){if(o){var I=s?crc32($):$;p[y]=isolateEvalWithHash(functionCache,I,$,p)}else p[y]=isolateEval($);p[y].scope=D}else p[y]=new Code($,D)}}return null!=p.$id&&(p=new DBRef(p.$ref,p.$id,p.$db)),p},isolateEvalWithHash=function(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=7,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},{"../binary":53,"../code":56,"../db_ref":57,"../double":58,"../float_parser":59,"../long":60,"../max_key":62,"../min_key":63,"../objectid":64,"../regexp":68,"../symbol":69,"../timestamp":70,util:98}],67:[function(t,e,r){(function(r){"use strict";var n=t("../float_parser").writeIEEE754,i=(t("../float_parser").readIEEE754,t("../long").Long),o=t("../map"),s=(t("../double").Double,t("../timestamp").Timestamp,t("../objectid").ObjectID,t("../symbol").Symbol,t("../code").Code,t("../regexp").BSONRegExp,t("../min_key").MinKey),a=(t("../max_key").MaxKey,t("../db_ref").DBRef,t("../binary").Binary),u=/\x00/,c=function(t){return"object"==typeof t&&"[object Date]"===Object.prototype.toString.call(t)},f=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},l=function(t,e,r,n){t[n++]=T.BSON_DATA_STRING;var i=t.write(e,n,"utf8");n=n+i+1,t[n-1]=0;var o=t.write(r,n+4,"utf8");return t[n+3]=o+1>>24&255,t[n+2]=o+1>>16&255,t[n+1]=o+1>>8&255,t[n]=o+1&255,n=n+4+o,t[n++]=0,n},h=function(t,e,r,o){if(Math.floor(r)===r&&r>=T.JS_INT_MIN&&r<=T.JS_INT_MAX)if(r>=T.BSON_INT32_MIN&&r<=T.BSON_INT32_MAX){t[o++]=T.BSON_DATA_INT;var s=t.write(e,o,"utf8");o+=s,t[o++]=0,t[o++]=255&r,t[o++]=r>>8&255,t[o++]=r>>16&255,t[o++]=r>>24&255}else if(r>=T.JS_INT_MIN&&r<=T.JS_INT_MAX){t[o++]=T.BSON_DATA_NUMBER;var s=t.write(e,o,"utf8");o+=s,t[o++]=0,n(t,r,o,"little",52,8),o+=8}else{t[o++]=T.BSON_DATA_LONG;var s=t.write(e,o,"utf8");o+=s,t[o++]=0;var a=i.fromNumber(r),u=a.getLowBits(),c=a.getHighBits();t[o++]=255&u,t[o++]=u>>8&255,t[o++]=u>>16&255,t[o++]=u>>24&255,t[o++]=255&c,t[o++]=c>>8&255,t[o++]=c>>16&255,t[o++]=c>>24&255}else{t[o++]=T.BSON_DATA_NUMBER;var s=t.write(e,o,"utf8");o+=s,t[o++]=0,n(t,r,o,"little",52,8),o+=8}return o},p=function(t,e,r,n){t[n++]=T.BSON_DATA_NULL;var i=t.write(e,n,"utf8");return n+=i,t[n++]=0,n},d=function(t,e,r,n){t[n++]=T.BSON_DATA_BOOLEAN;var i=t.write(e,n,"utf8");return n+=i,t[n++]=0,t[n++]=r?1:0,n},_=function(t,e,r,n){t[n++]=T.BSON_DATA_DATE;var o=t.write(e,n,"utf8");n+=o,t[n++]=0;var s=i.fromNumber(r.getTime()),a=s.getLowBits(),u=s.getHighBits();return t[n++]=255&a,t[n++]=a>>8&255,t[n++]=a>>16&255,t[n++]=a>>24&255,t[n++]=255&u,t[n++]=u>>8&255,t[n++]=u>>16&255,t[n++]=u>>24&255,n},y=function(t,e,r,n){t[n++]=T.BSON_DATA_REGEXP;var i=t.write(e,n,"utf8");if(n+=i,t[n++]=0,r.source&&null!=r.source.match(u))throw Error("value "+r.source+" must not contain null bytes");return n+=t.write(r.source,n,"utf8"),t[n++]=0,r.global&&(t[n++]=115),r.ignoreCase&&(t[n++]=105),r.multiline&&(t[n++]=109),t[n++]=0,n},g=function(t,e,r,n){t[n++]=T.BSON_DATA_REGEXP;var i=t.write(e,n,"utf8");return n+=i,t[n++]=0,n+=t.write(r.pattern,n,"utf8"),t[n++]=0,n+=t.write(r.options,n,"utf8"),t[n++]=0,n},v=function(t,e,r,n){null===r?t[n++]=T.BSON_DATA_NULL:r instanceof s?t[n++]=T.BSON_DATA_MIN_KEY:t[n++]=T.BSON_DATA_MAX_KEY;var i=t.write(e,n,"utf8");return n+=i,t[n++]=0,n},m=function(t,e,r,n){t[n++]=T.BSON_DATA_OID;var i=t.write(e,n,"utf8");return n+=i,t[n++]=0,t.write(r.id,n,"binary"),n+12},b=function(t,e,r,n){t[n++]=T.BSON_DATA_BINARY;var i=t.write(e,n,"utf8");n+=i,t[n++]=0;var o=r.length;return t[n++]=255&o,t[n++]=o>>8&255,t[n++]=o>>16&255,t[n++]=o>>24&255,t[n++]=T.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(t,n,0,o),n+=o},w=function(t,e,r,n,i,o,s,a){t[n++]=Array.isArray(r)?T.BSON_DATA_ARRAY:T.BSON_DATA_OBJECT;var u=t.write(e,n,"utf8");n+=u,t[n++]=0;var c=B(t,r,i,n,o+1,s,a);return c},E=function(t,e,r,n){t[n++]="Long"==r._bsontype?T.BSON_DATA_LONG:T.BSON_DATA_TIMESTAMP;var i=t.write(e,n,"utf8");n+=i,t[n++]=0;var o=r.getLowBits(),s=r.getHighBits();return t[n++]=255&o,t[n++]=o>>8&255,t[n++]=o>>16&255,t[n++]=o>>24&255,t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,n},O=function(t,e,r,i){t[i++]=T.BSON_DATA_NUMBER;var o=t.write(e,i,"utf8");return i+=o,t[i++]=0,n(t,r,i,"little",52,8),i+=8},A=function(t,e,r,n,i,o){t[n++]=T.BSON_DATA_CODE;var s=t.write(e,n,"utf8");n+=s,t[n++]=0;var a=r.toString(),u=t.write(a,n+4,"utf8")+1;return t[n]=255&u,t[n+1]=u>>8&255,t[n+2]=u>>16&255,t[n+3]=u>>24&255,n=n+4+u-1,t[n++]=0,n},S=function(t,e,r,n,i,o,s,a){if(null!=r.scope&&Object.keys(r.scope).length>0){t[n++]=T.BSON_DATA_CODE_W_SCOPE;var u=t.write(e,n,"utf8");n+=u,t[n++]=0;var c=n,f="string"==typeof r.code?r.code:r.code.toString();n+=4;var l=t.write(f,n+4,"utf8")+1;t[n]=255&l,t[n+1]=l>>8&255,t[n+2]=l>>16&255,t[n+3]=l>>24&255,t[n+4+l-1]=0,n=n+l+4;var h=B(t,r.scope,i,n,o+1,s,a);n=h-1;var p=h-c;t[c++]=255&p,t[c++]=p>>8&255,t[c++]=p>>16&255,t[c++]=p>>24&255,t[n++]=0}else{t[n++]=T.BSON_DATA_CODE;var u=t.write(e,n,"utf8");n+=u,t[n++]=0;var f=r.code.toString(),d=t.write(f,n+4,"utf8")+1;t[n]=255&d,t[n+1]=d>>8&255,t[n+2]=d>>16&255,t[n+3]=d>>24&255,n=n+4+d-1,t[n++]=0}return n},j=function(t,e,r,n){t[n++]=T.BSON_DATA_BINARY;var i=t.write(e,n,"utf8");n+=i,t[n++]=0;var o=r.value(!0),s=r.position;return t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,t[n++]=r.sub_type,r.sub_type==a.SUBTYPE_BYTE_ARRAY&&(t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255),o.copy(t,n,0,r.position),n+=r.position},N=function(t,e,r,n){t[n++]=T.BSON_DATA_SYMBOL;var i=t.write(e,n,"utf8");n+=i,t[n++]=0;var o=t.write(r.value,n+4,"utf8")+1;return t[n]=255&o,t[n+1]=o>>8&255,t[n+2]=o>>16&255,t[n+3]=o>>24&255,n=n+4+o-1,t[n++]=0,n},x=function(t,e,r,n,i,o){t[n++]=T.BSON_DATA_OBJECT;var s=t.write(e,n,"utf8");n+=s,t[n++]=0;var a,u=n;a=null!=r.db?B(t,{$ref:r.namespace,$id:r.oid,$db:r.db},!1,n,i+1,o):B(t,{$ref:r.namespace,$id:r.oid},!1,n,i+1,o);var c=a-u;return t[u++]=255&c,t[u++]=c>>8&255,t[u++]=c>>16&255,t[u++]=c>>24&255,a},B=function(t,e,n,i,s,a,B){i=i||0;var T=i+4;if(Array.isArray(e))for(var k=0;k>8&255,t[i++]=M>>16&255,t[i++]=M>>24&255,T},T={};T.functionCache={};T.BSON_DATA_NUMBER=1,T.BSON_DATA_STRING=2,T.BSON_DATA_OBJECT=3,T.BSON_DATA_ARRAY=4,T.BSON_DATA_BINARY=5,T.BSON_DATA_OID=7,T.BSON_DATA_BOOLEAN=8,T.BSON_DATA_DATE=9,T.BSON_DATA_NULL=10,T.BSON_DATA_REGEXP=11,T.BSON_DATA_CODE=13,T.BSON_DATA_SYMBOL=14,T.BSON_DATA_CODE_W_SCOPE=15,T.BSON_DATA_INT=16,T.BSON_DATA_TIMESTAMP=17,T.BSON_DATA_LONG=18,T.BSON_DATA_MIN_KEY=255,T.BSON_DATA_MAX_KEY=127,T.BSON_BINARY_SUBTYPE_DEFAULT=0,T.BSON_BINARY_SUBTYPE_FUNCTION=1,T.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,T.BSON_BINARY_SUBTYPE_UUID=3,T.BSON_BINARY_SUBTYPE_MD5=4,T.BSON_BINARY_SUBTYPE_USER_DEFINED=128,T.BSON_INT32_MAX=2147483647,T.BSON_INT32_MIN=-2147483648,T.BSON_INT64_MAX=Math.pow(2,63)-1,T.BSON_INT64_MIN=-Math.pow(2,63),T.JS_INT_MAX=9007199254740992,T.JS_INT_MIN=-9007199254740992;i.fromNumber(9007199254740992),i.fromNumber(-9007199254740992);e.exports=B}).call(this,t("buffer").Buffer)},{"../binary":53,"../code":56,"../db_ref":57,"../double":58,"../float_parser":59,"../long":60,"../map":61,"../max_key":62,"../min_key":63,"../objectid":64,"../regexp":68,"../symbol":69,"../timestamp":70,buffer:71}],68:[function(t,e,r){function n(t,e){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=t,this.options=e;for(var r=0;re||e>36)throw Error("radix out of range: "+e);if(this.isZero())return"0";if(this.isNegative()){if(this.equals(n.MIN_VALUE)){var r=n.fromNumber(e),i=this.div(r),o=i.multiply(r).subtract(this);return i.toString(e)+o.toInt().toString(e)}return"-"+this.negate().toString(e)}for(var s=n.fromNumber(Math.pow(e,6)),o=this,a="";;){var u=o.div(s),c=o.subtract(u.multiply(s)).toInt(),f=c.toString(e);if(o=u,o.isZero())return f+a;for(;f.length<6;)f="0"+f;a=""+f+a}},n.prototype.getHighBits=function(){return this.high_},n.prototype.getLowBits=function(){return this.low_},n.prototype.getLowBitsUnsigned=function(){return this.low_>=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!=this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},n.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},n.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(t){var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,f=0,l=0,h=0,p=0;return p+=o+c,h+=p>>>16,p&=65535,h+=i+u,l+=h>>>16,h&=65535,l+=r+a,f+=l>>>16,l&=65535,f+=e+s,f&=65535,n.fromBits(h<<16|p,f<<16|l)},n.prototype.subtract=function(t){return this.add(t.negate())},n.prototype.multiply=function(t){if(this.isZero())return n.ZERO;if(t.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return t.isOdd()?n.MIN_VALUE:n.ZERO;if(t.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&t.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,f=0,l=0,h=0,p=0;return p+=o*c,h+=p>>>16,p&=65535,h+=i*c,l+=h>>>16,h&=65535,h+=o*u,l+=h>>>16,h&=65535,l+=r*c,f+=l>>>16,l&=65535,l+=i*u,f+=l>>>16,l&=65535,l+=o*a,f+=l>>>16,l&=65535,f+=e*c+r*u+i*a+o*s,f&=65535,n.fromBits(h<<16|p,f<<16|l)},n.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(t.equals(n.ONE)||t.equals(n.NEG_ONE))return n.MIN_VALUE;if(t.equals(n.MIN_VALUE))return n.ONE;var e=this.shiftRight(1),r=e.div(t).shiftLeft(1);if(r.equals(n.ZERO))return t.isNegative()?n.ONE:n.NEG_ONE;var i=this.subtract(t.multiply(r)),o=r.add(i.div(t));return o}if(t.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();for(var s=n.ZERO,i=this;i.greaterThanOrEqual(t);){for(var r=Math.max(1,Math.floor(i.toNumber()/t.toNumber())),a=Math.ceil(Math.log(r)/Math.LN2),u=48>=a?1:Math.pow(2,a-48),c=n.fromNumber(r),f=c.multiply(t);f.isNegative()||f.greaterThan(i);)r-=u,c=n.fromNumber(r),f=c.multiply(t);c.isZero()&&(c=n.ONE),s=s.add(c),i=i.subtract(f)}return s},n.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(t){return n.fromBits(this.low_&t.low_,this.high_&t.high_)},n.prototype.or=function(t){return n.fromBits(this.low_|t.low_,this.high_|t.high_)},n.prototype.xor=function(t){return n.fromBits(this.low_^t.low_,this.high_^t.high_)},n.prototype.shiftLeft=function(t){if(t&=63,0==t)return this;var e=this.low_;if(32>t){var r=this.high_;return n.fromBits(e<>>32-t)}return n.fromBits(0,e<t){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>t)}return n.fromBits(e>>t-32,e>=0?0:-1)},n.prototype.shiftRightUnsigned=function(t){if(t&=63,0==t)return this;var e=this.high_;if(32>t){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>>t)}return 32==t?n.fromBits(e,0):n.fromBits(e>>>t-32,0)},n.fromInt=function(t){if(t>=-128&&128>t){var e=n.INT_CACHE_[t];if(e)return e}var r=new n(0|t,0>t?-1:0);return t>=-128&&128>t&&(n.INT_CACHE_[t]=r),r},n.fromNumber=function(t){return isNaN(t)||!isFinite(t)?n.ZERO:t<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:t+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:0>t?n.fromNumber(-t).negate():new n(t%n.TWO_PWR_32_DBL_|0,t/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(t,e){return new n(t,e)},n.fromString=function(t,e){if(0==t.length)throw Error("number format error: empty string");var r=e||10;if(2>r||r>36)throw Error("radix out of range: "+r);if("-"==t.charAt(0))return n.fromString(t.substring(1),r).negate();if(t.indexOf("-")>=0)throw Error('number format error: interior "-" character: '+t);for(var i=n.fromNumber(Math.pow(r,8)),o=n.ZERO,s=0;sa){var c=n.fromNumber(Math.pow(r,a));o=o.multiply(c).add(n.fromNumber(u))}else o=o.multiply(i),o=o.add(n.fromNumber(u))}return o},n.INT_CACHE_={},n.TWO_PWR_16_DBL_=65536,n.TWO_PWR_24_DBL_=1<<24,n.TWO_PWR_32_DBL_=n.TWO_PWR_16_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_31_DBL_=n.TWO_PWR_32_DBL_/2,n.TWO_PWR_48_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_16_DBL_,n.TWO_PWR_64_DBL_=n.TWO_PWR_32_DBL_*n.TWO_PWR_32_DBL_,n.TWO_PWR_63_DBL_=n.TWO_PWR_64_DBL_/2,n.ZERO=n.fromInt(0),n.ONE=n.fromInt(1),n.NEG_ONE=n.fromInt(-1),n.MAX_VALUE=n.fromBits(-1,2147483647),n.MIN_VALUE=n.fromBits(0,-2147483648),n.TWO_PWR_24_=n.fromInt(1<<24),e.exports=n,e.exports.Timestamp=n},{}],71:[function(t,e,r){function n(t,e,r){if(!(this instanceof n))return new n(t,e,r);var i,o=typeof t;if("number"===o)i=t>0?t>>>0:0;else if("string"===o)"base64"===e&&(t=O(t)),i=n.byteLength(t,e);else{if("object"!==o||null===t)throw new TypeError("must start with number, buffer, array or string");"Buffer"===t.type&&P(t.data)&&(t=t.data),i=+t.length>0?Math.floor(+t.length):0}if(this.length>R)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+R.toString(16)+" bytes");var s;n.TYPED_ARRAY_SUPPORT?s=n._augment(new Uint8Array(i)):(s=this,s.length=i,s._isBuffer=!0);var a;if(n.TYPED_ARRAY_SUPPORT&&"number"==typeof t.byteLength)s._set(t);else if(S(t))if(n.isBuffer(t))for(a=0;i>a;a++)s[a]=t.readUInt8(a);else for(a=0;i>a;a++)s[a]=(t[a]%256+256)%256;else if("string"===o)s.write(t,0,e);else if("number"===o&&!n.TYPED_ARRAY_SUPPORT&&!r)for(a=0;i>a;a++)s[a]=0;return s}function i(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;if(o%2!==0)throw new Error("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;n>s;s++){var a=parseInt(e.substr(2*s,2),16);if(isNaN(a))throw new Error("Invalid hex string");t[r+s]=a}return s}function o(t,e,r,n){var i=k(N(e),t,r,n);return i}function s(t,e,r,n){var i=k(x(e),t,r,n);return i}function a(t,e,r,n){return s(t,e,r,n)}function u(t,e,r,n){var i=k(T(e),t,r,n);return i}function c(t,e,r,n){var i=k(B(e),t,r,n,2);return i}function f(t,e,r){return 0===e&&r===t.length?I.fromByteArray(t):I.fromByteArray(t.slice(e,r))}function l(t,e,r){var n="",i="";r=Math.min(t.length,r);for(var o=e;r>o;o++)t[o]<=127?(n+=$(i)+String.fromCharCode(t[o]),i=""):i+="%"+t[o].toString(16);return n+$(i)}function h(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function p(t,e,r){return h(t,e,r)}function d(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",o=e;r>o;o++)i+=j(t[o]);return i}function _(t,e,r){for(var n=t.slice(e,r),i="",o=0;ot)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function g(t,e,r,i,o,s){if(!n.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>o||s>e)throw new TypeError("value is out of bounds");if(r+i>t.length)throw new TypeError("index out of range")}function v(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);o>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function m(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);o>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function b(t,e,r,n,i,o){if(e>i||o>e)throw new TypeError("value is out of bounds");if(r+n>t.length)throw new TypeError("index out of range")}function w(t,e,r,n,i){return i||b(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),D.write(t,e,r,n,23,4),r+4}function E(t,e,r,n,i){return i||b(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),D.write(t,e,r,n,52,8),r+8}function O(t){for(t=A(t).replace(M,"");t.length%4!==0;)t+="=";return t}function A(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function S(t){return P(t)||n.isBuffer(t)||t&&"object"==typeof t&&"number"==typeof t.length}function j(t){return 16>t?"0"+t.toString(16):t.toString(16)}function N(t){for(var e=[],r=0;r=n)e.push(n);else{var i=r;n>=55296&&57343>=n&&r++;for(var o=encodeURIComponent(t.slice(i,r+1)).substr(1).split("%"),s=0;s>8,n=e%256,i.push(n),i.push(r);return i}function T(t){return I.toByteArray(t)}function k(t,e,r,n,i){i&&(n-=n%i);for(var o=0;n>o&&!(o+r>=e.length||o>=t.length);o++)e[o+r]=t[o];return o}function $(t){try{return decodeURIComponent(t)}catch(t){return String.fromCharCode(65533)}}var I=t("base64-js"),D=t("ieee754"),P=t("is-array");r.Buffer=n,r.SlowBuffer=n,r.INSPECT_MAX_BYTES=50,n.poolSize=8192;var R=1073741823;n.TYPED_ARRAY_SUPPORT=function(){try{var t=new ArrayBuffer(0),e=new Uint8Array(t);return e.foo=function(){return 42},42===e.foo()&&"function"==typeof e.subarray&&0===new Uint8Array(1).subarray(1,1).byteLength}catch(t){return!1}}(),n.isBuffer=function(t){return!(null==t||!t._isBuffer)},n.compare=function(t,e){if(!n.isBuffer(t)||!n.isBuffer(e))throw new TypeError("Arguments must be Buffers");for(var r=t.length,i=e.length,o=0,s=Math.min(r,i);s>o&&t[o]===e[o];o++);return o!==s&&(r=t[o],i=e[o]),i>r?-1:r>i?1:0},n.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},n.concat=function(t,e){if(!P(t))throw new TypeError("Usage: Buffer.concat(list[, length])");if(0===t.length)return new n(0);if(1===t.length)return t[0];var r;if(void 0===e)for(e=0,r=0;r>>1;break;case"utf8":case"utf-8":r=N(t).length;break;case"base64":r=T(t).length;break;default:r=t.length}return r},n.prototype.length=void 0,n.prototype.parent=void 0,n.prototype.toString=function(t,e,r){var n=!1;if(e>>>=0,r=void 0===r||r===1/0?this.length:r>>>0,t||(t="utf8"),0>e&&(e=0),r>this.length&&(r=this.length),e>=r)return"";for(;;)switch(t){case"hex":return d(this,e,r);case"utf8":case"utf-8":return l(this,e,r);case"ascii":return h(this,e,r);case"binary":return p(this,e,r);case"base64":return f(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}},n.prototype.equals=function(t){if(!n.isBuffer(t))throw new TypeError("Argument must be a Buffer");return 0===n.compare(this,t)},n.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),""},n.prototype.compare=function(t){if(!n.isBuffer(t))throw new TypeError("Argument must be a Buffer");return n.compare(this,t)},n.prototype.get=function(t){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(t)},n.prototype.set=function(t,e){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(t,e)},n.prototype.write=function(t,e,r,n){if(isFinite(e))isFinite(r)||(n=r,r=void 0);else{var f=n;n=e,e=r,r=f}e=Number(e)||0;var l=this.length-e;r?(r=Number(r),r>l&&(r=l)):r=l,n=String(n||"utf8").toLowerCase();var h;switch(n){case"hex":h=i(this,t,e,r);break;case"utf8":case"utf-8":h=o(this,t,e,r);break;case"ascii":h=s(this,t,e,r);break;case"binary":h=a(this,t,e,r);break;case"base64":h=u(this,t,e,r);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":h=c(this,t,e,r);break;default:throw new TypeError("Unknown encoding: "+n)}return h},n.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},n.prototype.slice=function(t,e){var r=this.length;if(t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t),n.TYPED_ARRAY_SUPPORT)return n._augment(this.subarray(t,e));for(var i=e-t,o=new n(i,void 0,!0),s=0;i>s;s++)o[s]=this[s+t];return o},n.prototype.readUInt8=function(t,e){return e||y(t,1,this.length),this[t]},n.prototype.readUInt16LE=function(t,e){return e||y(t,2,this.length),this[t]|this[t+1]<<8},n.prototype.readUInt16BE=function(t,e){return e||y(t,2,this.length),this[t]<<8|this[t+1]},n.prototype.readUInt32LE=function(t,e){return e||y(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},n.prototype.readUInt32BE=function(t,e){return e||y(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},n.prototype.readInt8=function(t,e){return e||y(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},n.prototype.readInt16LE=function(t,e){e||y(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt16BE=function(t,e){e||y(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},n.prototype.readInt32LE=function(t,e){return e||y(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},n.prototype.readInt32BE=function(t,e){return e||y(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},n.prototype.readFloatLE=function(t,e){return e||y(t,4,this.length),D.read(this,t,!0,23,4)},n.prototype.readFloatBE=function(t,e){return e||y(t,4,this.length),D.read(this,t,!1,23,4)},n.prototype.readDoubleLE=function(t,e){return e||y(t,8,this.length),D.read(this,t,!0,52,8)},n.prototype.readDoubleBE=function(t,e){return e||y(t,8,this.length),D.read(this,t,!1,52,8)},n.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,1,255,0),n.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=t,e+1},n.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,2,65535,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8):v(this,t,e,!0),e+2},n.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,2,65535,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=t):v(this,t,e,!1),e+2},n.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,4,4294967295,0),n.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=t):m(this,t,e,!0),e+4},n.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,4,4294967295,0),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t):m(this,t,e,!1),e+4},n.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,1,127,-128),n.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=t,e+1},n.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,2,32767,-32768),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8):v(this,t,e,!0),e+2},n.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,2,32767,-32768),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=t):v(this,t,e,!1),e+2},n.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,4,2147483647,-2147483648),n.TYPED_ARRAY_SUPPORT?(this[e]=t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):m(this,t,e,!0),e+4},n.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||g(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),n.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=t):m(this,t,e,!1),e+4},n.prototype.writeFloatLE=function(t,e,r){return w(this,t,e,!0,r)},n.prototype.writeFloatBE=function(t,e,r){return w(this,t,e,!1,r)},n.prototype.writeDoubleLE=function(t,e,r){return E(this,t,e,!0,r)},n.prototype.writeDoubleBE=function(t,e,r){return E(this,t,e,!1,r)},n.prototype.copy=function(t,e,r,i){var o=this;if(r||(r=0),i||0===i||(i=this.length),e||(e=0),i!==r&&0!==t.length&&0!==o.length){if(r>i)throw new TypeError("sourceEnd < sourceStart");if(0>e||e>=t.length)throw new TypeError("targetStart out of bounds");if(0>r||r>=o.length)throw new TypeError("sourceStart out of bounds");if(0>i||i>o.length)throw new TypeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-es||!n.TYPED_ARRAY_SUPPORT)for(var a=0;s>a;a++)t[a+e]=this[a+r];else t._set(this.subarray(r,r+s),e)}},n.prototype.fill=function(t,e,r){if(t||(t=0),e||(e=0),r||(r=this.length),e>r)throw new TypeError("end < start");if(r!==e&&0!==this.length){if(0>e||e>=this.length)throw new TypeError("start out of bounds");if(0>r||r>this.length)throw new TypeError("end out of bounds");var n;if("number"==typeof t)for(n=e;r>n;n++)this[n]=t;else{var i=N(t.toString()),o=i.length;for(n=e;r>n;n++)this[n]=i[n%o]}return this}},n.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(n.TYPED_ARRAY_SUPPORT)return new n(this).buffer;for(var t=new Uint8Array(this.length),e=0,r=t.length;r>e;e+=1)t[e]=this[e];return t.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser")};var C=n.prototype;n._augment=function(t){return t.constructor=n,t._isBuffer=!0,t._get=t.get,t._set=t.set,t.get=C.get,t.set=C.set,t.write=C.write,t.toString=C.toString,t.toLocaleString=C.toString,t.toJSON=C.toJSON,t.equals=C.equals,t.compare=C.compare,t.copy=C.copy,t.slice=C.slice,t.readUInt8=C.readUInt8,t.readUInt16LE=C.readUInt16LE,t.readUInt16BE=C.readUInt16BE,t.readUInt32LE=C.readUInt32LE,t.readUInt32BE=C.readUInt32BE,t.readInt8=C.readInt8,t.readInt16LE=C.readInt16LE,t.readInt16BE=C.readInt16BE,t.readInt32LE=C.readInt32LE,t.readInt32BE=C.readInt32BE,t.readFloatLE=C.readFloatLE,t.readFloatBE=C.readFloatBE,t.readDoubleLE=C.readDoubleLE,t.readDoubleBE=C.readDoubleBE,t.writeUInt8=C.writeUInt8,t.writeUInt16LE=C.writeUInt16LE,t.writeUInt16BE=C.writeUInt16BE,t.writeUInt32LE=C.writeUInt32LE,t.writeUInt32BE=C.writeUInt32BE,t.writeInt8=C.writeInt8,t.writeInt16LE=C.writeInt16LE,t.writeInt16BE=C.writeInt16BE,t.writeInt32LE=C.writeInt32LE,t.writeInt32BE=C.writeInt32BE,t.writeFloatLE=C.writeFloatLE,t.writeFloatBE=C.writeFloatBE,t.writeDoubleLE=C.writeDoubleLE,t.writeDoubleBE=C.writeDoubleBE,t.fill=C.fill,t.inspect=C.inspect,t.toArrayBuffer=C.toArrayBuffer,t};var M=/[^+\/0-9A-z]/g},{"base64-js":52,ieee754:76,"is-array":78}],72:[function(t,e,r){function n(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function i(){var t=arguments,e=this.useColors;if(t[0]=(e?"%c":"")+this.namespace+(e?" %c":" ")+t[0]+(e?"%c ":" ")+"+"+r.humanize(this.diff),!e)return t;var n="color: "+this.color;t=[t[0],n,"color: inherit"].concat(Array.prototype.slice.call(t,1));var i=0,o=0;return t[0].replace(/%[a-z%]/g,function(t){"%%"!==t&&(i++,"%c"===t&&(o=i))}),t.splice(o,0,n),t}function o(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(t){try{null==t?r.storage.removeItem("debug"):r.storage.debug=t}catch(t){}}function a(){var t;try{t=r.storage.debug}catch(t){}return t}function u(){try{return window.localStorage}catch(t){}}r=e.exports=t("./debug"),r.log=o,r.formatArgs=i,r.save=s,r.load=a,r.useColors=n,r.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),r.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],r.formatters.j=function(t){return JSON.stringify(t)},r.enable(a())},{"./debug":73}],73:[function(t,e,r){function n(){return r.colors[f++%r.colors.length]}function i(t){function e(){}function i(){var t=i,e=+new Date,o=e-(c||e);t.diff=o,t.prev=c,t.curr=e,c=e,null==t.useColors&&(t.useColors=r.useColors()),null==t.color&&t.useColors&&(t.color=n());var s=Array.prototype.slice.call(arguments);s[0]=r.coerce(s[0]),"string"!=typeof s[0]&&(s=["%o"].concat(s));var a=0;s[0]=s[0].replace(/%([a-z%])/g,function(e,n){if("%%"===e)return e;a++;var i=r.formatters[n];if("function"==typeof i){var o=s[a];e=i.call(t,o),s.splice(a,1),a--}return e}),"function"==typeof r.formatArgs&&(s=r.formatArgs.apply(t,s));var u=i.log||r.log||console.log.bind(console);u.apply(t,s)}e.enabled=!1,i.enabled=!0;var o=r.enabled(t)?i:e;return o.namespace=t,o}function o(t){r.save(t);for(var e=(t||"").split(/[\s,]+/),n=e.length,i=0;n>i;i++)e[i]&&(t=e[i].replace(/\*/g,".*?"),"-"===t[0]?r.skips.push(new RegExp("^"+t.substr(1)+"$")):r.names.push(new RegExp("^"+t+"$")))}function s(){r.enable("")}function a(t){var e,n;for(e=0,n=r.skips.length;n>e;e++)if(r.skips[e].test(t))return!1;for(e=0,n=r.names.length;n>e;e++)if(r.names[e].test(t))return!0;return!1}function u(t){return t instanceof Error?t.stack||t.message:t}r=e.exports=i,r.coerce=u,r.disable=s,r.enable=o,r.enabled=a,r.humanize=t("ms"),r.names=[],r.skips=[],r.formatters={};var c,f=0},{ms:93}],74:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function o(t){return"number"==typeof t}function s(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!o(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,o,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],a(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(n=arguments.length,o=new Array(n-1),u=1;n>u;u++)o[u-1]=arguments[u];r.apply(this,o)}else if(s(r)){for(n=arguments.length,o=new Array(n-1),u=1;n>u;u++)o[u-1]=arguments[u];for(c=r.slice(),n=c.length,u=0;n>u;u++)c[u].apply(this,o)}return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?s(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,s(this._events[t])&&!this._events[t].warned){var r;r=a(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,o,a;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],o=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(r)){for(a=o;a-- >0;)if(r[a]===e||r[a].listener&&r[a].listener===e){n=a;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?i(t._events[e])?1:t._events[e].length:0}},{}],75:[function(t,e,r){function n(t,e){return function r(){if(!r.hookCalled){r.hookCalled=!0;var n=t.apply(e,arguments);n&&n.then&&n.then(function(){},function(){})}}}e.exports={hook:function(t,e,r){if(1!==arguments.length||"object"!=typeof t){var i=this.prototype||this,o=i._pres=i._pres||{},s=i._posts=i._posts||{};return o[t]=o[t]||[],s[t]=s[t]||[],i[t]=function(){var o,s=this,a=arguments[arguments.length-1],u=this._pres[t],c=this._posts[t],f=u.length,l=-1,h=i[t].numAsyncPres,p=function(t){return t?d(t):void(--h||y.apply(s,o))},d=function(t){if("function"==typeof a)return a(t);if(r)return r.call(s,t);throw t},_=function(){if(arguments[0]instanceof Error)return d(arguments[0]);var t,e,r=Array.prototype.slice.call(arguments);if(!r.length||null==arguments[0]&&"function"==typeof a||(o=r),++l>1,f=-7,l=r?i-1:0,h=r?-1:1,p=t[e+l];for(l+=h,o=p&(1<<-f)-1,p>>=-f,f+=a;f>0;o=256*o+t[e+l],l+=h,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+l],l+=h,f-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:(p?-1:1)*(1/0);s+=Math.pow(2,n),o-=c}return(p?-1:1)*s*Math.pow(2,o-n)},r.write=function(t,e,r,n,i,o){var s,a,u,c=8*o-i-1,f=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,_=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),e+=s+l>=1?h/u:h*Math.pow(2,1-l),e*u>=2&&(s++,u/=2),s+l>=f?(a=0,s=f):s+l>=1?(a=(e*u-1)*Math.pow(2,i),s+=l):(a=e*Math.pow(2,l-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,c-=8);t[r+p-d]|=128*_}},{}],77:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],78:[function(t,e,r){var n=Array.isArray,i=Object.prototype.toString;e.exports=n||function(t){return!!t&&"[object Array]"==i.call(t)}},{}],79:[function(t,e,r){(function(t){"use strict";function r(){this._pres={},this._posts={}}r.prototype.execPre=function(e,r,n){var i=this._pres[e]||[],o=i.length,s=i.numAsync||0,a=0,u=s,c=!1;if(!o)return t.nextTick(function(){n(null)});var f=function(){if(!(a>=o)){var e=i[a];if(e.isAsync)e.fn.call(r,function(t){if(t){if(c)return;return c=!0,n(t)}++a,f.apply(r,arguments)},function(t){if(t){if(c)return;return c=!0,n(t)}return 0===--s?n(null):void 0});else if(e.fn.length>0){var l=[function(t){if(t){if(c)return;return c=!0,n(t)}return++a>=o?u>0?void 0:n(null):void f.apply(r,arguments)}];if(arguments.length>=2)for(var h=1;h=o)return u>0?void 0:t.nextTick(function(){n(null)});f()}}};f()},r.prototype.execPost=function(e,r,n,i){var o=this._posts[e]||[],s=o.length,a=0;if(!s)return t.nextTick(function(){i.apply(null,[null].concat(n))});var u=function(){var t=o[a];if(t.length>n.length)t.apply(r,n.concat(function(t){return t?i(t):++a>=s?i.apply(null,[null].concat(n)):void u()}));else{if(t.apply(r,n),++a>=s)return i.apply(null,[null].concat(n));u()}};u()},r.prototype.wrap=function(t,e,r,n,i){var o=n.length>0?n[n.length-1]:null,s=this;this.execPre(t,r,function(a){if(a){if("function"==typeof o)return o(a)}else{var u="function"==typeof o?n.length-1:n.length;e.apply(r,n.slice(0,u).concat(function(){if(arguments[0])return"function"==typeof o?o(arguments[0]):void 0;i&&"function"==typeof o&&o.apply(r,arguments);var e=Array.prototype.slice.call(arguments,1);s.execPost(t,r,e,function(){return arguments[0]?"function"==typeof o?o(arguments[0]):void 0:"function"!=typeof o||i?void 0:o.apply(r,arguments)})}))}})},r.prototype.createWrapper=function(t,e,r){var n=this;return function(){var i=Array.prototype.slice.call(arguments);n.wrap(t,e,r,i)}},r.prototype.pre=function(t,e,r,n){"boolean"!=typeof arguments[1]&&(n=r,r=e,e=!1),this._pres[t]=this._pres[t]||[];var i=this._pres[t];return e&&(i.numAsync=i.numAsync||0,++i.numAsync),i.push({fn:r,isAsync:e}),this},r.prototype.post=function(t,e){return(this._posts[t]=this._posts[t]||[]).push(e),this},r.prototype.clone=function(){var t=new r;for(var e in this._pres)t._pres[e]=this._pres[e].slice();for(var e in this._posts)t._posts[e]=this._posts[e].slice();return t},e.exports=r}).call(this,t("g5I+bs"))},{"g5I+bs":94}],80:[function(t,e,r){e.exports=r=t("./lib")},{"./lib":81}],81:[function(t,e,r){function n(t){return t}r.get=function(t,e,i,o){var s;"function"==typeof i&&(i.length<2?(o=i,i=void 0):(s=i,i=void 0)),o||(o=n);var a="string"==typeof t?t.split("."):t;if(!Array.isArray(a))throw new TypeError("Invalid `path`. Must be either string or array");for(var u,c=e,f=0;fp;++p)if(f=c[p],"$"!=f){if(Array.isArray(h)&&!/^\d+$/.test(f)){var _=c.slice(p);if(!l&&Array.isArray(e))for(var y=0;y0},o.prototype.fulfill=function(){return this.safeEmit.apply(this,i(o.SUCCESS,arguments))},o.prototype.reject=function(t){if(this.ended&&!this.hasRejectListeners())throw t;return this.safeEmit(o.FAILURE,t)},o.prototype.resolve=function(t,e){return t?this.reject(t):this.fulfill(e)},o.prototype.onFulfill=function(t){if(!t)return this;if("function"!=typeof t)throw new TypeError("fn should be a function");return this.on(o.SUCCESS,t)},o.prototype.onReject=function(t){if(!t)return this;if("function"!=typeof t)throw new TypeError("fn should be a function");return this.on(o.FAILURE,t)},o.prototype.onResolve=function(t){if(!t)return this;if("function"!=typeof t)throw new TypeError("fn should be a function");return this.on(o.FAILURE,function(e){t.call(this,e)}),this.on(o.SUCCESS,function(){t.apply(this,i(null,arguments))}),this},o.prototype.then=function(t,e){var r=new o;return"function"==typeof t?this.onFulfill(s(r,t)):this.onFulfill(r.fulfill.bind(r)),"function"==typeof e?this.onReject(s(r,e)):this.onReject(r.reject.bind(r)),r},o.prototype.end=o.prototype.catch=function(t){return t||this.hasRejectListeners()||(t=function(t){throw t}),this.onReject(t),this.ended=!0,this},o.trace=function(t,e){t.then(function(){console.log("%s fulfill %j",e,n(arguments))},function(){console.log("%s reject %j",e,n(arguments))})},o.prototype.chain=function(t){var e=this;return e.onFulfill(t.fulfill.bind(t)),e.onReject(t.reject.bind(t)),t},o.prototype.all=function(t){var e=new o;return this.then(t).then(function(t){var r,n=0,i=[];return t.length||e.resolve(),t.forEach(function(t,o){r||(n++,t.then(function(t){r||(i[o]=t,--n,0==n&&e.fulfill(i))},function(t){r||(r=t,e.reject(t))}))}),e},e.reject.bind(e)),e},o.hook=function(t){var e=new o,r=new o,n=function(){return--i,0==i&&r.fulfill(),r},i=1,s=e;return t.forEach(function(t){s=s.then(function(){var e=new o;return i++,t(e.resolve.bind(e),n),e})}),s=s.then(n),e.resolve(),s},o.fulfilled=function(){var t=new o;return t.fulfill.apply(t,arguments),t},o.rejected=function(t){return(new o).reject(t)},o.deferred=function(){var t=new o;return{promise:t,reject:t.reject.bind(t),resolve:t.fulfill.bind(t),callback:t.resolve.bind(t)}}}).call(this,t("g5I+bs"))},{events:74,"g5I+bs":94,util:98}],83:[function(t,e,r){"use strict";function n(){}function i(t){return function(){throw new Error("collection."+t+" not implemented")}}for(var o=["find","findOne","update","remove","count","distinct","findAndModify","aggregate","findStream"],s=0,a=o.length;a>s;++s){var u=o[s];n.prototype[u]=i(u)}e.exports=r=n,n.methods=o},{}],84:[function(t,e,r){"use strict";var n=t("../env");if("unknown"==n.type)throw new Error("Unknown environment");e.exports=t(n.isNode?"./node":n.isMongo?"./collection":"./collection")},{"../env":86,"./collection":83,"./node":85}],85:[function(t,e,r){"use strict";function n(t){this.collection=t,this.collectionName=t.collectionName}var i=t("./collection"),o=t("../utils");o.inherits(n,i),n.prototype.find=function(t,e,r){this.collection.find(t,e,function(t,e){return t?r(t):void e.toArray(r)})},n.prototype.findOne=function(t,e,r){this.collection.findOne(t,e,r)},n.prototype.count=function(t,e,r){this.collection.count(t,e,r)},n.prototype.distinct=function(t,e,r,n){this.collection.distinct(t,e,r,n)},n.prototype.update=function(t,e,r,n){this.collection.update(t,e,r,n)},n.prototype.remove=function(t,e,r){this.collection.remove(t,e,r)},n.prototype.findAndModify=function(t,e,r,n){var i=Array.isArray(r.sort)?r.sort:[];this.collection.findAndModify(t,i,e,r,n)},n.prototype.findStream=function(t,e,r){return this.collection.find(t,e).stream(r)},n.prototype.findCursor=function(t,e){return this.collection.find(t,e)},e.exports=r=n},{"../utils":89,"./collection":83}],86:[function(t,e,r){(function(t,n,i){"use strict";r.isNode="undefined"!=typeof t&&"object"==typeof e&&"object"==typeof n&&"function"==typeof i&&t.argv,r.isMongo=!r.isNode&&"function"==typeof printjson&&"function"==typeof ObjectId&&"function"==typeof rs&&"function"==typeof sh,r.isBrowser=!r.isNode&&!r.isMongo&&"undefined"!=typeof window,r.type=r.isNode?"node":r.isMongo?"mongo":r.isBrowser?"browser":"unknown"}).call(this,t("g5I+bs"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{buffer:71,"g5I+bs":94}],87:[function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n(t,e);var r=this.constructor.prototype;this.op=r.op||void 0,this.options={},this.setOptions(r.options),this._conditions=r._conditions?c.clone(r._conditions):{},this._fields=r._fields?c.clone(r._fields):void 0,this._update=r._update?c.clone(r._update):void 0,this._path=r._path||void 0,this._distinct=r._distinct||void 0,this._collection=r._collection||void 0,this._traceFunction=r._traceFunction||void 0,e&&this.setOptions(e),t&&(t.find&&t.remove&&t.update?this.collection(t):this.find(t))}function i(t,e,r){if(Array.isArray(t.sort))throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`");if(r&&r.$meta){var n=t.sort||(t.sort={});return void(n[e]={$meta:r.$meta})}var i=String(r||1).toLowerCase();if(!/^(?:ascending|asc|descending|desc|1|-1)$/.test(i))throw c.isArray(r)&&(r="["+r+"]"),new TypeError("Invalid sort value: {"+e+": "+r+" }");var n=t.sort||(t.sort={}),o=r.toString().replace("asc","1").replace("ascending","1").replace("desc","-1").replace("descending","-1");n[e]=parseInt(o,10)}function o(t,e,r){if(t.sort=t.sort||[],!Array.isArray(t.sort))throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`");r.toString().replace("asc","1").replace("ascending","1").replace("desc","-1").replace("descending","-1");t.sort.push([e,r])}var s=t("sliced"),a=t("assert"),u=t("util"),c=t("./utils"),f=t("debug")("mquery"),l="$geoWithin";Object.defineProperty(n,"use$geoWithin",{get:function(){return"$geoWithin"==l},set:function(t){l=!0===t?"$geoWithin":"$within"}}),n.prototype.toConstructor=function(){function t(e,r){return this instanceof t?void n.call(this,e,r):new t(e,r)}c.inherits(t,n);var e=t.prototype;return e.options={},e.setOptions(this.options),e.op=this.op,e._conditions=c.clone(this._conditions),e._fields=c.clone(this._fields),e._update=c.clone(this._update),e._path=this._path,e._distinct=this._distinct,e._collection=this._collection,e._traceFunction=this._traceFunction,t},n.prototype.setOptions=function(t){if(!t||!c.isObject(t))return this;for(var e,r=c.keys(t),n=0;nn;++n){var o=t[n];if(o){var s="-"==o[0]?0:1;0===s&&(o=o.substring(1)),e[o]=s}}return this}if(c.isObject(t)&&!Array.isArray(t)){for(var a=c.keys(t),n=0;no;++o)this.slice(n[o],r[n[o]]);return this}this._ensurePath("slice"),t=this._path,e=arguments[0]}else 2===arguments.length?"number"==typeof arguments[0]?(this._ensurePath("slice"),t=this._path,e=s(arguments)):(t=arguments[0],e=arguments[1]):3===arguments.length&&(t=arguments[0],e=s(arguments,1));var a=this._fields||(this._fields={});return a[t]={$slice:e},this},n.prototype.sort=function(t){if(!t)return this;var e;this._validate("sort");var r=typeof t;if(Array.isArray(t)){e=t.length;for(var n=0;nn;++n){var s=t[n];if(s){var a="-"==s[0]?-1:1;-1===a&&(s=s.substring(1)),i(this.options,s,a)}}return this}if(c.isObject(t)){for(var u=c.keys(t),n=0;n1&&!n.prototype.read.deprecationWarningIssued&&(console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."),n.prototype.read.deprecationWarningIssued=!0),this.options.readPreference=c.readPref(t),this},n.prototype.tailable=function(){return this._validate("tailable"),this.options.tailable=arguments.length?!!arguments[0]:!0,this},n.prototype.merge=function(t){if(!t)return this;if(!n.canMerge(t))throw new TypeError("Invalid argument. Expected instanceof mquery or plain object");return t instanceof n?(t._conditions&&c.merge(this._conditions,t._conditions),t._fields&&(this._fields||(this._fields={}),c.merge(this._fields,t._fields)),t.options&&(this.options||(this.options={}),c.merge(this.options,t.options)),t._update&&(this._update||(this._update={}),c.mergeClone(this._update,t._update)),t._distinct&&(this._distinct=t._distinct),this):(c.merge(this._conditions,t),this)},n.prototype.find=function(t,e){if(this.op="find","function"==typeof t?(e=t,t=void 0):n.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,i=this._optionsForExec();return i.fields=this._fieldsForExec(),f("find",this._collection.collectionName,r,i),e=this._wrapCallback("find",e,{conditions:r,options:i}),this._collection.find(r,i,c.tick(e)),this},n.prototype.cursor=function(t){if(this.op){if("find"!==this.op)throw new TypeError(".cursor only support .find method")}else this.find(t);var e=this._conditions,r=this._optionsForExec();return r.fields=this._fieldsForExec(),f("findCursor",this._collection.collectionName,e,r),this._collection.findCursor(e,r)},n.prototype.findOne=function(t,e){if(this.op="findOne","function"==typeof t?(e=t,t=void 0):n.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,i=this._optionsForExec();return i.fields=this._fieldsForExec(),f("findOne",this._collection.collectionName,r,i),e=this._wrapCallback("findOne",e,{conditions:r,options:i}),this._collection.findOne(r,i,c.tick(e)),this},n.prototype.count=function(t,e){if(this.op="count",this._validate(),"function"==typeof t?(e=t,t=void 0):n.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,i=this._optionsForExec();return f("count",this._collection.collectionName,r,i),e=this._wrapCallback("count",e,{conditions:r,options:i}),this._collection.count(r,i,c.tick(e)),this},n.prototype.distinct=function(t,e,r){if(this.op="distinct",this._validate(),!r){switch(typeof e){case"function":r=e,"string"==typeof t&&(e=t,t=void 0);break;case"undefined":case"string":break;default:throw new TypeError("Invalid `field` argument. Must be string or function")}switch(typeof t){case"function":r=t,t=e=void 0;break;case"string":e=t,t=void 0}}if("string"==typeof e&&(this._distinct=e),n.canMerge(t)&&this.merge(t),!r)return this;if(!this._distinct)throw new Error("No value for `distinct` has been declared");var i=this._conditions,o=this._optionsForExec();return f("distinct",this._collection.collectionName,i,o),r=this._wrapCallback("distinct",r,{conditions:i,options:o}),this._collection.distinct(this._distinct,i,o,c.tick(r)),this},n.prototype.update=function(t,e,r,i){this.op="update";var o;switch(arguments.length){case 3:"function"==typeof r&&(i=r,r=void 0);break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0);break;case 1:switch(typeof t){case"function":i=t,t=r=e=void 0;break;case"boolean":o=t,t=void 0;break;default:e=t,t=r=void 0}}if(n.canMerge(t)&&this.merge(t),e&&this._mergeUpdate(e),c.isObject(r)&&this.setOptions(r),!o&&!i)return this;if(!this._update||!this.options.overwrite&&0===c.keys(this._update).length)return i&&c.soon(i.bind(null,null,0)),this;r=this._optionsForExec(),i||(r.safe=!1);var t=this._conditions;return e=this._updateForExec(),f("update",this._collection.collectionName,t,e,r),i=this._wrapCallback("update",i,{conditions:t,doc:e,options:r}),this._collection.update(t,e,r,c.tick(i)),this},n.prototype.remove=function(t,e){this.op="remove";var r;if("function"==typeof t?(e=t,t=void 0):n.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var i=this._optionsForExec();e||(i.safe=!1);var o=this._conditions;return f("remove",this._collection.collectionName,o,i),e=this._wrapCallback("remove",e,{conditions:o,options:i}),this._collection.remove(o,i,c.tick(e)),this},n.prototype.findOneAndUpdate=function(t,e,r,i){switch(this.op="findOneAndUpdate",this._validate(),arguments.length){case 3:"function"==typeof r&&(i=r,r={});break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0),r=void 0;break;case 1:"function"==typeof t?(i=t,t=r=e=void 0):(e=t,t=r=void 0)}return n.canMerge(t)&&this.merge(t),e&&this._mergeUpdate(e),r&&this.setOptions(r),i?this._findAndModify("update",i):this},n.prototype.findOneAndRemove=function(t,e,r){return this.op="findOneAndRemove",this._validate(),"function"==typeof e?(r=e,e=void 0):"function"==typeof t&&(r=t,t=void 0),n.canMerge(t)&&this.merge(t),e&&this.setOptions(e),r?this._findAndModify("remove",r):this},n.prototype._findAndModify=function(t,e){a.equal("function",typeof e);var r,n,i=this._optionsForExec();if("remove"==t)i.remove=!0;else if("new"in i||(i.new=!0),"upsert"in i||(i.upsert=!1),n=this._updateForExec(),!n){if(!i.upsert)return this.findOne(e);n={$set:{}}}var r=this._fieldsForExec();r&&(i.fields=r);var o=this._conditions;return f("findAndModify",this._collection.collectionName,o,n,i),e=this._wrapCallback("findAndModify",e,{conditions:o,doc:n,options:i}),this._collection.findAndModify(o,n,i,c.tick(e)),this},n.prototype._wrapCallback=function(t,e,r){var i=this._traceFunction||n.traceFunction;if(i){r.collectionName=this._collection.collectionName;var o=i&&i.call(null,t,r,this),s=(new Date).getTime();return function(t,r){if(o){var n=(new Date).getTime()-s;o.call(null,t,r,n)}e&&e.apply(null,arguments)}}return e},n.prototype.setTraceFunction=function(t){return this._traceFunction=t,this},n.prototype.exec=function(t,e){switch(typeof t){case"function":e=t,t=null;break;case"string":this.op=t}a.ok(this.op,"Missing query type: (find, update, etc)"),("update"==this.op||"remove"==this.op)&&(e||(e=!0));var r=this;return"function"!=typeof e?new n.Promise(function(t,e){r[r.op](function(n,i){n?e(n):t(i),r=t=e=null})}):void this[this.op](e)},n.prototype.thunk=function(){var t=this;return function(e){t.exec(e)}},n.prototype.then=function(t,e){var r=this,i=new n.Promise(function(t,e){r.exec(function(n,i){n?e(n):t(i),r=t=e=null})});return i.then(t,e)},n.prototype.stream=function(t){if("find"!=this.op)throw new Error("stream() is only available for find");var e=this._conditions,r=this._optionsForExec();return r.fields=this._fieldsForExec(),f("stream",this._collection.collectionName,e,r,t),this._collection.findStream(e,r,t)},n.prototype.selected=function(){return!!(this._fields&&Object.keys(this._fields).length>0)},n.prototype.selectedInclusively=function(){if(!this._fields)return!1;var t=Object.keys(this._fields);if(0===t.length)return!1;for(var e=0;e0)return"field selection and slice";var e,r=Object.keys(n.distinct);return r.every(function(r){return t.options[r]?(e=r,!1):!0}),e},n.distinct.select=n.distinct.slice=n.distinct.sort=n.distinct.limit=n.distinct.skip=n.distinct.batchSize=n.distinct.comment=n.distinct.maxScan=n.distinct.snapshot=n.distinct.hint=n.distinct.tailable=!0,n.findOneAndUpdate=n.findOneAndRemove=function(t){var e,r=Object.keys(n.findOneAndUpdate);return r.every(function(r){return t.options[r]?(e=r,!1):!0}),e},n.findOneAndUpdate.limit=n.findOneAndUpdate.skip=n.findOneAndUpdate.batchSize=n.findOneAndUpdate.maxScan=n.findOneAndUpdate.snapshot=n.findOneAndUpdate.hint=n.findOneAndUpdate.tailable=n.findOneAndUpdate.comment=!0,n.count=function(t){if(t._fields&&Object.keys(t._fields).length>0)return"field selection and slice";var e,r=Object.keys(n.count);return r.every(function(r){return t.options[r]?(e=r,!1):!0}),e},n.count.slice=n.count.batchSize=n.count.comment=n.count.maxScan=n.count.snapshot=n.count.tailable=!0},{}],89:[function(t,e,r){(function(e,n){"use strict";function i(t){function e(){}if(arguments.length>1)throw new Error("Adding properties is not supported");return e.prototype=t,new e}var o=t("regexp-clone"),s=r.clone=function t(e,n){if(void 0===e||null===e)return e;if(Array.isArray(e))return r.cloneArray(e,n);if(e.constructor){if(/ObjectI[dD]$/.test(e.constructor.name))return"function"==typeof e.clone?e.clone():new e.constructor(e.id);if("ReadPreference"===e._type&&e.isValid&&e.toObject)return"function"==typeof e.clone?e.clone():new e.constructor(e.mode,t(e.tags,n));if("Binary"==e._bsontype&&e.buffer&&e.value)return"function"==typeof e.clone?e.clone():new e.constructor(e.value(!0),e.sub_type);if("Date"===e.constructor.name||"Function"===e.constructor.name)return new e.constructor(+e);if("RegExp"===e.constructor.name)return o(e);if("Buffer"===e.constructor.name)return r.cloneBuffer(e)}return u(e)?r.cloneObject(e,n):e.valueOf?e.valueOf():void 0};r.cloneObject=function(t,e){var r,n,i,o,a,u=e&&e.retainKeyOrder,c=e&&e.minimize,f={};if(u)for(o in t)i=s(t[o],e),c&&"undefined"==typeof i||(r||(r=!0),f[o]=i);else for(n=Object.keys(t),a=n.length;a--;)o=n[a],i=s(t[o],e),c&&"undefined"==typeof i||(r||(r=!0),f[o]=i);return c?r&&f:f},r.cloneArray=function(t,e){for(var r=[],n=0,i=t.length;i>n;n++)r.push(s(t[n],e));return r},r.tick=function(t){return"function"==typeof t?function(){var e=arguments;c(function(){t.apply(this,e)})}:void 0},r.merge=function t(e,n){for(var i,o=Object.keys(n),s=o.length;s--;)i=o[s],"undefined"==typeof e[i]?e[i]=n[i]:r.isObject(n[i])?t(e[i],n[i]):e[i]=n[i]},r.mergeClone=function t(e,n){for(var i,o=Object.keys(n),a=o.length;a--;)i=o[a],"undefined"==typeof e[i]?e[i]=s(n[i],{retainKeyOrder:1}):r.isObject(n[i])?t(e[i],n[i]):e[i]=s(n[i],{retainKeyOrder:1})};r.readPref=function(t){switch(t){case"p":t="primary";break;case"pp":t="primaryPreferred";break;case"s":t="secondary";break;case"sp":t="secondaryPreferred";break;case"n":t="nearest"}return t};var a=Object.prototype.toString,u=(r.toString=function(t){return a.call(t)},r.isObject=function(t){return"[object Object]"==r.toString(t)});r.isArray=function(t){return Array.isArray(t)||"object"==typeof t&&"[object Array]"==r.toString(t)};r.keys=Object.keys||function(t){var e=[];for(var r in t)t.hasOwnProperty(r)&&e.push(r);return e},r.create="function"==typeof Object.create?Object.create:i,r.inherits=function(t,e){t.prototype=r.create(e.prototype),t.prototype.constructor=t};var c=r.soon="function"==typeof setImmediate?setImmediate:e.nextTick;r.cloneBuffer=function(t){var e=new n(t.length);return t.copy(e,0,0,t.length),e},r.isArgumentsObject=function(t){return"[object Arguments]"===Object.prototype.toString.call(t)}}).call(this,t("g5I+bs"),t("buffer").Buffer)},{buffer:71,"g5I+bs":94,"regexp-clone":95}],90:[function(t,e,r){(function(t,n){!function(t){if("object"==typeof r&&"undefined"!=typeof e)e.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i;"undefined"!=typeof window?i=window:"undefined"!=typeof n?i=n:"undefined"!=typeof self&&(i=self),i.Promise=t()}}(function(){var e,r,i;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){var r=e[s][1][t];return i(r?r:t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},n.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(t){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},f.hasDevTools?(u.isStatic&&(u=function(t){setTimeout(t,0)}),n.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):this._schedule(function(){setTimeout(function(){t.call(e,r)},100)})},n.prototype.invoke=function(t,e,r){this._trampolineEnabled?o.call(this,t,e,r):this._schedule(function(){t.call(e,r)})},n.prototype.settlePromises=function(t){this._trampolineEnabled?s.call(this,t):this._schedule(function(){t._settlePromises()})}):(n.prototype.invokeLater=i,n.prototype.invoke=o,n.prototype.settlePromises=s),n.prototype.invokeFirst=function(t,e,r){this._normalQueue.unshift(t,e,r),this._queueTick()},n.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},n.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},n.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},n.prototype._reset=function(){this._isTickUsed=!1},e.exports=new n,e.exports.firstLineError=a},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(u._setBoundTo(a),a instanceof t){var f={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,f),a._then(o,s,u._progress,u,f)}else u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return s._setBoundTo(o),o instanceof t?o._then(function(){s._resolveCallback(i)},s._reject,s._progress,s,null):s._resolveCallback(i),s}}},{}],4:[function(t,e,r){"use strict";function n(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise.js")();o.noConflict=n,e.exports=o},{"./promise.js":23}],5:[function(t,e,r){"use strict";var n=Object.create;if(n){var i=n(null),o=n(null);i[" size"]=o[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e,r){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(e,r,n){"use strict";r.exports=function(){function r(t){this._parent=t;var e=this._length=1+(void 0===t?0:t._length);w(this,r),e>32&&this.uncycle()}function n(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function s(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function u(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+c(e)+">, no stack trace)"}function c(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,f=n-2;f>=0;--f)e[f]._length=c,c++;return}}}},r.prototype.parent=function(){return this._parent},r.prototype.hasParent=function(){return void 0!==this._parent},r.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=r.parseStackAndMessage(t),a=e.message,u=[e.stack],c=this;void 0!==c;)u.push(s(c.stack.split("\n"))),c=c._parent;o(u),i(u),p.notEnumerableProp(t,"stack",n(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},r.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?a(t):[" (No stack trace)"],{message:r,stack:s(e)}},r.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+y(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},r.unhandledRejection=function(t){r.formatAndLogError(t,"^--- With additional stack trace: ")},r.isSupported=function(){return"function"==typeof w},r.fireRejectionEvent=function(t,e,n,i){var o=!1;try{"function"==typeof e&&(o=!0,"rejectionHandled"===t?e(i):e(n,i))}catch(t){h.throwLater(t)}var s=!1;try{s=E(t,n,i)}catch(t){s=!0,h.throwLater(t)}var a=!1;if(b)try{a=b(t.toLowerCase(),{reason:n,promise:i})}catch(t){a=!0,h.throwLater(t)}s||o||a||"unhandledRejection"!==t||r.formatAndLogError(n,"Unhandled rejection ")};var v=function(){return!1},m=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;r.setBounds=function(t,e){if(r.isSupported()){for(var n,i,o=t.stack.split("\n"),s=e.stack.split("\n"),a=-1,u=-1,c=0;ca||0>u||!n||!i||n!==i||a>=u||(v=function(t){if(d.test(t))return!0;var e=f(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var b,w=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():u(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,y=e;var r=Error.captureStackTrace;return v=function(t){return d.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,y=e,g=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(t){i="stack"in t}return"stack"in n||!i||"number"!=typeof Error.stackTraceLimit?(y=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?u(e):e.toString()},null):(_=t,y=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),E=function(){if(p.isNode)return function(e,r,n){return"rejectionHandled"===e?t.emit(e,n):t.emit(e,r,n)};var e=!1,r=!0;try{var n=new self.CustomEvent("test");e=n instanceof CustomEvent}catch(t){}if(!e)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(t){r=!1}r&&(b=function(t,r){var n;return e?n=new self.CustomEvent(t,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(t,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&t.stderr.isTTY?l=function(e){t.stderr.write(""+e+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),r}},{"./async.js":2,"./util.js":38}],8:[function(t,e,r){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundValue(),u=0,c=this._instances.length;c>u;++u){var f=this._instances[u],l=f===Error||null!=f&&f.prototype instanceof Error;if(l&&t instanceof f){var h=s(r).call(o,t);return h===a?(e.e=h.e,e):h}if("function"==typeof f&&!l){var p=n(f,t);if(p===a){t=a.e;break}if(p){var h=s(r).call(o,t);return h===a?(e.e=h.e,e):h}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e,r){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(e,r,n){"use strict";r.exports=function(r,n){var i,o,s=r._getDomain,a=e("./async.js"),u=e("./errors.js").Warning,c=e("./util.js"),f=c.canAttachTrace,l=c.isNode&&(!!t.env.BLUEBIRD_DEBUG||"development"===t.env.NODE_ENV);return c.isNode&&0==t.env.BLUEBIRD_DEBUG&&(l=!1),l&&a.disableTrampolineIfNecessary(),r.prototype._ignoreRejections=function(){this._unsetRejectionIsUnhandled(),this._bitField=16777216|this._bitField},r.prototype._ensurePossibleRejectionHandled=function(){0===(16777216&this._bitField)&&(this._setRejectionIsUnhandled(),a.invokeLater(this._notifyUnhandledRejection,this,void 0))},r.prototype._notifyUnhandledRejectionIsHandled=function(){n.fireRejectionEvent("rejectionHandled",i,void 0,this)},r.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),n.fireRejectionEvent("unhandledRejection",o,t,this)}},r.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},r.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},r.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},r.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},r.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},r.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},r.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},r.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},r.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},r.prototype._captureStackTrace=function(){return l&&(this._trace=new n(this._peekContext())),this},r.prototype._attachExtraTrace=function(t,e){if(l&&f(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=n.parseStackAndMessage(t);c.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),c.notEnumerableProp(t,"__stackCleaned__",!0)}}},r.prototype._warn=function(t){var e=new u(t),r=this._peekContext();if(r)r.attachExtraTrace(e);else{var i=n.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}n.formatAndLogError(e,"")},r.onPossiblyUnhandledRejection=function(t){var e=s();o="function"==typeof t?null===e?t:e.bind(t):void 0},r.onUnhandledRejectionHandled=function(t){var e=s();i="function"==typeof t?null===e?t:e.bind(t):void 0},r.longStackTraces=function(){if(a.haveItemsQueued()&&l===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");l=n.isSupported(),l&&a.disableTrampolineIfNecessary()},r.hasLongStackTraces=function(){return l&&n.isSupported()},n.isSupported()||(r.longStackTraces=function(){},l=!1),function(){return l}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e,r){"use strict";var n=t("./util.js"),i=n.isPrimitive;e.exports=function(t){var e=function(){return this},r=function(){throw this},n=function(){},o=function(){throw void 0},s=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype.return=t.prototype.thenReturn=function(r){return void 0===r?this.then(n):i(r)?this._then(s(r,2),void 0,void 0,void 0,void 0):(r instanceof t&&r._ignoreRejections(),this._then(e,void 0,void 0,r,void 0))},t.prototype.throw=t.prototype.thenThrow=function(t){return void 0===t?this.then(o):i(t)?this._then(s(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e,r){"use strict";function n(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return f(r,Error),r}function i(t){return this instanceof i?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5.js"),u=a.freeze,c=t("./util.js"),f=c.inherits,l=c.notEnumerableProp,h=n("Warning","warning"),p=n("CancellationError","cancellation error"),d=n("TimeoutError","timeout error"),_=n("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(t){o=n("TypeError","type error"),s=n("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),g=0;g0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e,r){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace();var i=c();this._callback=null===i?e:i.bind(e),this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,f.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=e._getDomain,f=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,d={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===d){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundValue();this._promise._pushContext();var f=h(u).call(c,t,r,o);if(this._promise._popContext(),f===p)return this._reject(f.e);var l=i(f,this._promise);if(l instanceof e){if(l=l._target(),l._isPending())return a>=1&&this._inFlight++,n[r]=d,l._proxyPromiseArray(this,r);if(!l._isFulfilled())return this._reject(l._reason());f=l._value()}n[r]=f}var _=++this._totalResolved;_>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e,r){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e.try=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e,r){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundValue(),[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundValue(),i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundValue(),t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e,r){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var f=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(f),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(e,r,n){"use strict";r.exports=function(){function r(t){if("function"!=typeof t)throw new h("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==r)throw new h("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==p&&this._resolveFromResolver(t)}function n(t){var e=new r(p);e._fulfillmentHandler0=t,e._rejectionHandler0=t,e._progressHandler0=t,e._promise0=t,e._receiver0=t,e._settledValue=t}var i,o=function(){return new h("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},s=function(){return new r.PromiseInspection(this._target())},a=function(t){return r.reject(new h(t))},u=e("./util.js");i=u.isNode?function(){var e=t.domain;return void 0===e&&(e=null),e}:function(){return null},u.notEnumerableProp(r,"_getDomain",i);var c={},f=e("./async.js"),l=e("./errors.js"),h=r.TypeError=l.TypeError;r.RangeError=l.RangeError,r.CancellationError=l.CancellationError,r.TimeoutError=l.TimeoutError,r.OperationalError=l.OperationalError,r.RejectionError=l.OperationalError,r.AggregateError=l.AggregateError;var p=function(){},d={},_={e:null},y=e("./thenables.js")(r,p),g=e("./promise_array.js")(r,p,y,a),v=e("./captured_trace.js")(),m=e("./debuggability.js")(r,v),b=e("./context.js")(r,v,m),w=e("./catch_filter.js")(_),E=e("./promise_resolver.js"),O=E._nodebackForPromise,A=u.errorObj,S=u.tryCatch;return r.prototype.toString=function(){return"[object Promise]"},r.prototype.caught=r.prototype.catch=function(t){var e=arguments.length;if(e>1){var n,i=new Array(e-1),o=0;for(n=0;e-1>n;++n){var s=arguments[n];if("function"!=typeof s)return r.reject(new h("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new w(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},r.prototype.reflect=function(){return this._then(s,s,void 0,this,void 0)},r.prototype.then=function(t,e,r){if(m()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+u.classString(t);arguments.length>1&&(n+=", "+u.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},r.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},r.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,d,void 0)},r.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},r.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},r.prototype.all=function(){return new g(this).promise()},r.prototype.error=function(t){return this.caught(u.originatesFromRejection,t)},r.is=function(t){return t instanceof r},r.fromNode=function(t){var e=new r(p),n=S(t)(O(e));return n===A&&e._rejectCallback(n.e,!0,!0),e},r.all=function(t){return new g(t).promise()},r.defer=r.pending=function(){var t=new r(p);return new E(t)},r.cast=function(t){var e=y(t);if(!(e instanceof r)){var n=e;e=new r(p),e._fulfillUnchecked(n)}return e},r.resolve=r.fulfilled=r.cast,r.reject=r.rejected=function(t){var e=new r(p);return e._captureStackTrace(),e._rejectCallback(t,!0),e},r.setScheduler=function(t){if("function"!=typeof t)throw new h("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=f._schedule;return f._schedule=t,e},r.prototype._then=function(t,e,n,o,s){var a=void 0!==s,u=a?s:new r(p);a||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===o&&(o=this._boundTo),a||u._setIsMigrated());var l=c._addCallbacks(t,e,n,u,o,i());return c._isResolved()&&!c._isSettlePromisesQueued()&&f.invoke(c._settlePromiseAtPostResolution,c,l), +u},r.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},r.prototype._length=function(){return 131071&this._bitField},r.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},r.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},r.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},r.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},r.prototype._setRejected=function(){this._bitField=134217728|this._bitField},r.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},r.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},r.prototype._isFinal=function(){return(33554432&this._bitField)>0},r.prototype._cancellable=function(){return(67108864&this._bitField)>0},r.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},r.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},r.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},r.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},r.prototype._isMigrated=function(){return(4194304&this._bitField)>0},r.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];if(e!==c)return void 0===e&&this._isBound()?this._boundValue():e},r.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},r.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},r.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},r.prototype._boundValue=function(){var t=this._boundTo;return void 0!==t&&t instanceof r?t.isFulfilled()?t.value():void 0:t},r.prototype._migrateCallbacks=function(t,e){var n=t._fulfillmentHandlerAt(e),i=t._rejectionHandlerAt(e),o=t._progressHandlerAt(e),s=t._promiseAt(e),a=t._receiverAt(e);s instanceof r&&s._setIsMigrated(),void 0===a&&(a=c),this._addCallbacks(n,i,o,s,a,null)},r.prototype._addCallbacks=function(t,e,r,n,i,o){var s=this._length();if(s>=131066&&(s=0,this._setLength(0)),0===s)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=null===o?t:o.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===o?e:o.bind(e)),"function"==typeof r&&(this._progressHandler0=null===o?r:o.bind(r));else{var a=5*s-5;this[a+3]=n,this[a+4]=i,"function"==typeof t&&(this[a+0]=null===o?t:o.bind(t)),"function"==typeof e&&(this[a+1]=null===o?e:o.bind(e)),"function"==typeof r&&(this[a+2]=null===o?r:o.bind(r))}return this._setLength(s+1),s},r.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},r.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},r.prototype._resolveCallback=function(t,e){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(o(),!1,!0);var n=y(t,this);if(!(n instanceof r))return this._fulfill(t);var i=1|(e?4:0);this._propagateFrom(n,i);var s=n._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},r.prototype._rejectCallback=function(t,e,r){r||u.markAsOriginatingFromRejection(t);var n=u.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},r.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=S(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===A&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},r.prototype._settlePromiseFromHandler=function(t,e,r,n){if(!n._isRejected()){n._pushContext();var i;if(i=e!==d||this._isRejected()?S(t).call(e,r):S(t).apply(this._boundValue(),r),n._popContext(),i===A||i===n||i===_){var s=i===n?o():i.e;n._rejectCallback(s,!1,!0)}else n._resolveCallback(i)}},r.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},r.prototype._followee=function(){return this._rejectionHandler0},r.prototype._setFollowee=function(t){this._rejectionHandler0=t},r.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},r.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},r.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},r.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},r.prototype._settlePromiseAt=function(t){var e=this._promiseAt(t),n=e instanceof r;if(n&&e._isMigrated())return e._unsetIsMigrated(),f.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,a=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,a,s,e):i.call(a,s,e):a instanceof g?a._isResolved()||(this._isFulfilled()?a._promiseFulfilled(s,e):a._promiseRejected(s,e)):n&&(this._isFulfilled()?e._fulfill(s):e._reject(s,o)),t>=4&&4===(31&t)&&f.invokeLater(this._setLength,this,0)},r.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},r.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},r.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},r.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},r.prototype._queueSettlePromises=function(){f.settlePromises(this),this._setSettlePromisesQueued()},r.prototype._fulfillUnchecked=function(t){if(t===this){var e=o();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},r.prototype._rejectUncheckedCheckError=function(t){var e=u.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},r.prototype._rejectUnchecked=function(t,e){if(t===this){var r=o();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void f.throwLater(function(t){throw"stack"in t&&f.invokeFirst(v.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},r.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},u.notEnumerableProp(r,"_makeSelfResolutionError",o),e("./progress.js")(r,g),e("./method.js")(r,p,y,a),e("./bind.js")(r,p,y),e("./finally.js")(r,_,y),e("./direct_resolve.js")(r),e("./synchronous_inspection.js")(r),e("./join.js")(r,g,y,p),r.Promise=r,e("./map.js")(r,g,a,y,p),e("./cancel.js")(r),e("./using.js")(r,a,y,b),e("./generators.js")(r,a,p,y),e("./nodeify.js")(r),e("./call_get.js")(r),e("./props.js")(r,g,y,a),e("./race.js")(r,p,y,a),e("./reduce.js")(r,g,a,y,p),e("./settle.js")(r,g),e("./some.js")(r,g,a),e("./promisify.js")(r,p),e("./any.js")(r),e("./each.js")(r,p),e("./timers.js")(r,p),e("./filter.js")(r,p),u.toFastProperties(r),u.toFastProperties(r.prototype),n({a:1}),n({b:2}),n({c:3}),n(1),n(function(){}),n(void 0),n(!1),n(new r(p)),v.setBounds(f.firstLineError,u.lastLineError),r}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e,r){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function t(r,s){var a=n(this._values,this._promise);if(a instanceof e){if(a=a._target(),this._values=a,!a._isFulfilled())return a._isPending()?void a._then(t,this._reject,void 0,this,s):void this._reject(a._reason());if(a=a._value(),!u(a)){var c=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(c)}}else if(!u(a))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===a.length)return void(-5===s?this._resolveEmptyArray():this._resolve(o(s)));var f=this.getActualLength(a.length);this._length=f,this._values=this.shouldCopyValues()?new Array(f):this._values;for(var l=this._promise,h=0;f>h;++h){var p=this._isResolved(),d=n(a[h],l);d instanceof e?(d=d._target(),p?d._ignoreRejections():d._isPending()?d._proxyPromiseArray(this,h):d._isFulfilled()?this._promiseFulfilled(d._value(),h):this._promiseRejected(d._reason(),h)):p||this._promiseFulfilled(d,h)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t,e){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e,r){"use strict";function n(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(n(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var r=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),a=1;o>a;++a)s[a-1]=arguments[a];t._fulfill(s)}else t._fulfill(r);t=null}}}var s,a=t("./util.js"),u=a.maybeWrapAsError,c=t("./errors.js"),f=c.TimeoutError,l=c.OperationalError,h=a.haveGetters,p=t("./es5.js"),d=/^(?:name|message|stack|cause)$/;if(s=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=o(t),this.callback=this.asCallback},h){var _={get:function(){return o(this.promise)}};p.defineProperty(s.prototype,"asCallback",_),p.defineProperty(s.prototype,"callback",_)}s._nodebackForPromise=o,s.prototype.toString=function(){return"[object PromiseResolver]"},s.prototype.resolve=s.prototype.fulfill=function(t){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},s.prototype.reject=function(t){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},s.prototype.progress=function(t){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},s.prototype.cancel=function(t){this.promise.cancel(t)},s.prototype.timeout=function(){this.reject(new f("timeout"))},s.prototype.isResolved=function(){return this.promise.isResolved()},s.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=s},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e,r){"use strict";e.exports=function(e,r){function n(t){return!E.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(t){return!1}}function o(t,e,r){var n=p.getDataPropertyOrDefault(t,e+r,b);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],f=o[s+1],l=c+e;if(n===S)t[l]=S(c,h,c,f,e);else{var d=n(f,function(){return S(c,h,c,f,e)});p.notEnumerableProp(d,"__isPromisified__",!0),t[l]=d}}return p.toFastProperties(t),t}function f(t,e){return S(t,e,void 0,t)}var l,h={},p=t("./util.js"),d=t("./promise_resolver.js")._nodebackForPromise,_=p.withAppended,y=p.maybeWrapAsError,g=p.canEvaluate,v=t("./errors").TypeError,m="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],E=new RegExp("^(?:"+w.join("|")+")$"),O=function(t){return p.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},A=function(t){return t.replace(/([$])/,"\\$")},S=g?l:u;e.promisify=function(t,e){if("function"!=typeof t)throw new v("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=f(t,arguments.length<2?h:e);return p.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new v("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=O);var i=e.promisifier;if("function"!=typeof i&&(i=S),!p.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=p.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e,r){"use strict";function n(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityh;++h){var d=t[h];(void 0!==d||h in t)&&e.cast(d)._then(f,l,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e,r){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0);var p=c();this._callback=null===p?r:p.bind(r),this._accum=n,l||f.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=e._getDomain,f=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,f=this._valuesPhase;if(!f)for(f=this._valuesPhase=new Array(s),o=0;s>o;++o)f[o]=0;if(o=f[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,f[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?f[r]=1:(f[r]=2,this._accum=t),c){for(var l,d=this._callback,_=this._promise._boundValue(),y=this._reducingIndex;s>y;++y)if(o=f[y],2!==o){if(1!==o)return;if(t=n[y],this._promise._pushContext(),u?(a.push(t),l=h(d).call(_,t,y,s)):l=h(d).call(_,this._accum,t,y,s),this._promise._popContext(),l===p)return this._reject(l.e);var g=i(l,this._promise);if(g instanceof e){if(g=g._target(),g._isPending())return f[y]=4,g._proxyPromiseArray(this,y);if(!g._isFulfilled())return this._reject(g._reason());l=g._value()}this._reducingIndex=y+1,this._accum=l}else this._reducingIndex=y+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(e,r,i){"use strict";var o,s=e("./util"),a=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(s.isNode&&"undefined"==typeof MutationObserver){var u=n.setImmediate,c=t.nextTick;o=s.isRecentNode?function(t){u.call(n,t)}:function(e){c.call(t,e)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?o="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:a:(o=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},o.isStatic=!0);r.exports=o},{"./util":38}],32:[function(t,e,r){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e,r){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e,r){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var f=new e(r);return t._then(f._fulfillUnchecked,f._rejectUncheckedCheckError,f._progressUnchecked,f,null),f}var l=a.tryCatch(i)(t);if(l===u){n&&n._pushContext();var f=e.reject(l.e);return n&&n._popContext(),f}if("function"==typeof l)return s(t,l,n)}return t}function i(t){return t.then}function o(t){return f.call(t,"_promise0")}function s(t,n,i){function o(t){f&&(f._resolveCallback(t),f=null)}function s(t){f&&(f._rejectCallback(t,h,!0),f=null)}function c(t){f&&"function"==typeof f._progress&&f._progress(t)}var f=new e(r),l=f;i&&i._pushContext(),f._captureStackTrace(),i&&i._popContext();var h=!0,p=a.tryCatch(n).call(t,o,s,c);return h=!1,f&&p===u&&(f._rejectCallback(p.e,!0,!0),f=null),l}var a=t("./util.js"),u=a.errorObj,c=a.isObject,f={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e,r){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){var r;!o.isPrimitive(e)&&e instanceof Error?r=e:("string"!=typeof e&&(e="operation timed out"),r=new s(e)),o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e,r){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var f=a(t[o++]);if(f instanceof e&&f._isDisposable()){try{f=n(f._getDisposer().tryDispose(r),t.promise)}catch(t){return s(t)}if(f instanceof e)return f._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new y;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function f(t){var e=new y;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function l(t,e,r){this._data=t,this._promise=e,this._context=r}function h(t,e,r){this.constructor$(t,e,r)}function p(t){return l.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var d=t("./errors.js").TypeError,_=t("./util.js").inherits,y=e.PromiseInspection;l.prototype.data=function(){return this._data},l.prototype.promise=function(){return this._promise},l.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},l.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},l.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},_(h,l),h.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");var s,a=!0;2===t&&Array.isArray(arguments[0])?(s=arguments[0],t=s.length,a=!1):(s=arguments,t--);for(var u=new Array(t),h=0;t>h;++h){var d=s[h];if(l.isDisposer(d)){var _=d;d=d.promise(),d._setDisposable(_)}else{var y=n(d);y instanceof e&&(d=y._then(p,null,null,{resources:u,index:h},void 0))}u[h]=d}var g=e.settle(u).then(o).then(function(t){g._pushContext();var e;try{e=a?i.apply(void 0,t):i.call(void 0,t)}finally{g._popContext()}return e})._then(c,f,void 0,u,void 0);return u.promise=g,g},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new h(t,this,i());throw new d}}},{"./errors.js":13,"./util.js":38}],38:[function(e,r,n){"use strict";function i(){try{var t=N;return N=null,t.apply(this,arguments)}catch(t){return j.e=t,j}}function o(t){return N=t,i}function s(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function a(t){return!s(t)}function u(t){return s(t)?new Error(g(t)):t}function c(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function f(t,e,r){if(!O.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(s(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return O.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=O.names(t.prototype),r=O.isES5&&e.length>1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=T.test(t+"")&&O.names(t).length>0; +if(r||n||i)return!0}return!1}catch(t){return!1}}function d(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return k.test(t)}function y(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function g(t){try{return t+""}catch(t){return"[no string representation]"}}function v(t){try{l(t,"isOperational",!0)}catch(t){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return t instanceof Error&&O.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function E(t,e,r){for(var n=O.names(t),i=0;i10||e[0]>0}(),I.isNode&&I.toFastProperties(t);try{throw new Error}catch(t){I.lastLineError=t}r.exports=I},{"./es5.js":14}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,t("g5I+bs"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"g5I+bs":94}],91:[function(t,e,r){e.exports=r=t("./lib/sliced")},{"./lib/sliced":92}],92:[function(t,e,r){e.exports=function(t,e,r){var n=[],i=t.length;if(0===i)return n;var o=0>e?Math.max(0,e+i):e||0;for(void 0!==r&&(i=0>r?r+i:r);i-- >o;)n[i-o]=t[i];return n}},{}],93:[function(t,e,r){function n(t){if(t=""+t,!(t.length>1e4)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*l;case"days":case"day":case"d":return r*f;case"hours":case"hour":case"hrs":case"hr":case"h":return r*c;case"minutes":case"minute":case"mins":case"min":case"m":return r*u;case"seconds":case"second":case"secs":case"sec":case"s":return r*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r}}}}function i(t){return t>=f?Math.round(t/f)+"d":t>=c?Math.round(t/c)+"h":t>=u?Math.round(t/u)+"m":t>=a?Math.round(t/a)+"s":t+"ms"}function o(t){return s(t,f,"day")||s(t,c,"hour")||s(t,u,"minute")||s(t,a,"second")||t+" ms"}function s(t,e,r){return e>t?void 0:1.5*e>t?Math.floor(t/e)+" "+r:Math.ceil(t/e)+" "+r+"s"}var a=1e3,u=60*a,c=60*u,f=24*c,l=365.25*f;e.exports=function(t,e){return e=e||{},"string"==typeof t?n(t):e.long?o(t):i(t)}},{}],94:[function(t,e,r){function n(){}var i=e.exports={};i.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var r=[];return window.addEventListener("message",function(t){var e=t.source;if((e===window||null===e)&&"process-tick"===t.data&&(t.stopPropagation(),r.length>0)){var n=r.shift();n()}},!0),function(t){r.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),i.title="browser",i.browser=!0,i.env={},i.argv=[],i.on=n,i.addListener=n,i.once=n,i.off=n,i.removeListener=n,i.removeAllListeners=n,i.emit=n,i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")}},{}],95:[function(t,e,r){function n(t){return"object"==typeof t&&"[object RegExp]"==i.call(t)}var i=Object.prototype.toString;e.exports=r=function(t){if(!n(t))throw new TypeError("Not a RegExp");var e=[];return t.global&&e.push("g"),t.multiline&&e.push("m"),t.ignoreCase&&e.push("i"),new RegExp(t.source,e.join(""))}},{}],96:[function(t,e,r){e.exports=t(92)},{}],97:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],98:[function(t,e,r){(function(e,n){function i(t,e){var n={seen:[],stylize:s};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),_(e)?n.showHidden=e:e&&r._extend(n,e),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),u(n,t,n.depth)}function o(t,e){var r=i.styles[e];return r?"["+i.colors[r][0]+"m"+t+"["+i.colors[r][1]+"m":t}function s(t,e){return t}function a(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}function u(t,e,n){if(t.customInspect&&e&&j(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return m(i)||(i=u(t,i,n)),i}var o=c(t,e);if(o)return o;var s=Object.keys(e),_=a(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(e)),S(e)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(e);if(0===s.length){if(j(e)){var y=e.name?": "+e.name:"";return t.stylize("[Function"+y+"]","special")}if(E(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(A(e))return t.stylize(Date.prototype.toString.call(e),"date");if(S(e))return f(e)}var g="",v=!1,b=["{","}"];if(d(e)&&(v=!0,b=["[","]"]),j(e)){var w=e.name?": "+e.name:"";g=" [Function"+w+"]"}if(E(e)&&(g=" "+RegExp.prototype.toString.call(e)),A(e)&&(g=" "+Date.prototype.toUTCString.call(e)),S(e)&&(g=" "+f(e)),0===s.length&&(!v||0==e.length))return b[0]+g+b[1];if(0>n)return E(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);var O;return O=v?l(t,e,n,_,s):s.map(function(r){return h(t,e,n,_,r,v)}),t.seen.pop(),p(O,g,b)}function c(t,e){if(w(e))return t.stylize("undefined","undefined");if(m(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}return v(e)?t.stylize(""+e,"number"):_(e)?t.stylize(""+e,"boolean"):y(e)?t.stylize("null","null"):void 0}function f(t){return"["+Error.prototype.toString.call(t)+"]"}function l(t,e,r,n,i){for(var o=[],s=0,a=e.length;a>s;++s)k(e,String(s))?o.push(h(t,e,r,n,String(s),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(h(t,e,r,n,i,!0))}),o}function h(t,e,r,n,i,o){var s,a,c;if(c=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]},c.get?a=c.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):c.set&&(a=t.stylize("[Setter]","special")),k(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(c.value)<0?(a=y(r)?u(t,c.value,null):u(t,c.value,r-1),a.indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n"))):a=t.stylize("[Circular]","special")),w(s)){if(o&&i.match(/^\d+$/))return a;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function p(t,e,r){var n=0,i=t.reduce(function(t,e){return n++,e.indexOf("\n")>=0&&n++,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1]:r[0]+e+" "+t.join(", ")+" "+r[1]}function d(t){return Array.isArray(t)}function _(t){return"boolean"==typeof t}function y(t){return null===t}function g(t){return null==t}function v(t){return"number"==typeof t}function m(t){return"string"==typeof t}function b(t){return"symbol"==typeof t}function w(t){return void 0===t}function E(t){return O(t)&&"[object RegExp]"===x(t)}function O(t){return"object"==typeof t&&null!==t}function A(t){return O(t)&&"[object Date]"===x(t)}function S(t){return O(t)&&("[object Error]"===x(t)||t instanceof Error)}function j(t){return"function"==typeof t}function N(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||"undefined"==typeof t}function x(t){return Object.prototype.toString.call(t)}function B(t){return 10>t?"0"+t.toString(10):t.toString(10)}function T(){var t=new Date,e=[B(t.getHours()),B(t.getMinutes()),B(t.getSeconds())].join(":");return[t.getDate(),P[t.getMonth()],e].join(" ")}function k(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var $=/%[sdj%]/g;r.format=function(t){if(!m(t)){for(var e=[],r=0;r=o)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),a=n[r];o>r;a=n[++r])s+=y(a)||!O(a)?" "+a:" "+i(a);return s},r.deprecate=function(t,i){function o(){if(!s){if(e.throwDeprecation)throw new Error(i);e.traceDeprecation?console.trace(i):console.error(i),s=!0}return t.apply(this,arguments)}if(w(n.process))return function(){return r.deprecate(t,i).apply(this,arguments)};if(e.noDeprecation===!0)return t;var s=!1;return o};var I,D={};r.debuglog=function(t){if(w(I)&&(I=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!D[t])if(new RegExp("\\b"+t+"\\b","i").test(I)){var n=e.pid;D[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else D[t]=function(){};return D[t]},r.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=_,r.isNull=y,r.isNullOrUndefined=g,r.isNumber=v,r.isString=m,r.isSymbol=b,r.isUndefined=w,r.isRegExp=E,r.isObject=O,r.isDate=A,r.isError=S,r.isFunction=j,r.isPrimitive=N,r.isBuffer=t("./support/isBuffer");var P=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];r.log=function(){console.log("%s - %s",T(),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!O(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("g5I+bs"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":97,"g5I+bs":94,inherits:77}]},{},[2]); \ No newline at end of file diff --git a/node_modules/mongoose/lib/aggregate.js b/node_modules/mongoose/lib/aggregate.js index 4efd40f..306f796 100644 --- a/node_modules/mongoose/lib/aggregate.js +++ b/node_modules/mongoose/lib/aggregate.js @@ -80,8 +80,9 @@ Aggregate.prototype.bind = function (model) { */ Aggregate.prototype.append = function () { - var args = utils.args(arguments) - , arg; + var args = (1 === arguments.length && util.isArray(arguments[0])) + ? arguments[0] + : utils.args(arguments); if (!args.every(isOperator)) { throw new Error("Arguments must be aggregate pipeline operators"); @@ -270,7 +271,7 @@ Aggregate.prototype.unwind = function () { return this.append.apply(this, args.map(function (arg) { return { $unwind: '$' + arg }; })); -} +}; /** * Appends a new $sort operator to this aggregate pipeline. diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js index bb630c8..d960887 100644 --- a/node_modules/mongoose/lib/document.js +++ b/node_modules/mongoose/lib/document.js @@ -456,7 +456,9 @@ Document.prototype.set = function (path, val, type, options) { && (!path[key].constructor || 'Object' == path[key].constructor.name) && 'virtual' != pathtype && !(this.$__path(pathName) instanceof MixedSchema) - && !(this.schema.paths[pathName] && this.schema.paths[pathName].options.ref)) { + && !(this.schema.paths[pathName] && + this.schema.paths[pathName].options && + this.schema.paths[pathName].options.ref)) { this.set(path[key], prefix + key, constructing); } else if (strict) { if ('real' === pathtype || 'virtual' === pathtype) { @@ -730,7 +732,8 @@ Document.prototype.get = function (path, type) { */ Document.prototype.$__path = function (path) { - var adhocs = this.$__.adhocPaths + var base = this.$__ + , adhocs = (base) ? base.adhocPaths : undefined , adhocType = adhocs && adhocs[path]; if (adhocType) { diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js index c1a2954..415cd86 100644 --- a/node_modules/mongoose/lib/query.js +++ b/node_modules/mongoose/lib/query.js @@ -1757,7 +1757,8 @@ Query.prototype.update = function (conditions, doc, options, callback) { // validate the update part of the query var castedDoc; try { - castedDoc = this._castUpdate(doc, options && options.overwrite); + castedDoc = this._castUpdate(utils.clone(doc, { retainKeyOrder: true }), + options && options.overwrite); } catch (err) { if (callback) { callback(err); @@ -1970,7 +1971,7 @@ Query.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) { if ('$each' in val) { obj[key] = { - $each: this._castUpdateVal(schema, val.$each, op) + $each: this._castUpdateVal(schema, val.$each, op) } if (val.$slice) { @@ -2014,6 +2015,11 @@ Query.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) { delete obj[key]; } } else { + if (op === '$rename') { + hasKeys = true; + return; + } + hasKeys = true; obj[key] = this._castUpdateVal(schema, val, op, key); } @@ -2646,7 +2652,17 @@ Query.prototype.tailable = function (val, opts) { val = true; } - if (opts && opts.awaitdata) this.options.awaitdata = true; + if (opts && typeof opts === 'object') { + for (var key in opts) { + if (key === 'awaitdata') { + // For backwards compatibility + this.options[key] = !!opts[key]; + } else { + this.options[key] = opts[key]; + } + } + } + return Query.base.tailable.call(this, val); } diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js index 5bb68fc..2999e7b 100644 --- a/node_modules/mongoose/lib/schema.js +++ b/node_modules/mongoose/lib/schema.js @@ -301,7 +301,7 @@ Schema.prototype.path = function (path, obj) { branch[last] = utils.clone(obj); - this.paths[path] = Schema.interpretAsType(path, obj); + this.paths[path] = Schema.interpretAsType(path, obj, this.options); return this; }; @@ -313,7 +313,7 @@ Schema.prototype.path = function (path, obj) { * @api private */ -Schema.interpretAsType = function (path, obj) { +Schema.interpretAsType = function (path, obj, options) { if (obj.constructor && obj.constructor.name != 'Object') obj = { type: obj }; @@ -343,7 +343,7 @@ Schema.interpretAsType = function (path, obj) { } else if (cast && (!cast.type || cast.type.type) && 'Object' == cast.constructor.name && Object.keys(cast).length) { - return new Types.DocumentArray(path, new Schema(cast), obj); + return new Types.DocumentArray(path, new Schema(cast, options), obj); } return new Types.Array(path, cast || Types.Mixed, obj); @@ -897,4 +897,3 @@ Schema.Types = require('./schema/index'); Types = Schema.Types; Query = require('./query'); var ObjectId = exports.ObjectId = Types.ObjectId; - diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js index 91a59e0..6e18f25 100644 --- a/node_modules/mongoose/lib/schema/buffer.js +++ b/node_modules/mongoose/lib/schema/buffer.js @@ -112,6 +112,9 @@ SchemaBuffer.prototype.cast = function (value, doc, init) { var type = typeof value; if ('string' == type || 'number' == type || Array.isArray(value)) { + if (type === 'number') { + value = [value]; + } var ret = new MongooseBuffer(value, [this.path, doc]); return ret; } diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js index 5f288d1..ef59cb0 100644 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ b/node_modules/mongoose/lib/schema/documentarray.js @@ -20,7 +20,6 @@ var Subdocument = require('../types/embedded'); */ function DocumentArray (key, schema, options) { - // compile an embedded document for this schema function EmbeddedDocument () { Subdocument.apply(this, arguments); diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js index 0568917..c80e202 100644 --- a/node_modules/mongoose/lib/schema/string.js +++ b/node_modules/mongoose/lib/schema/string.js @@ -216,10 +216,14 @@ SchemaString.prototype.match = function match (regExp, message) { var msg = message || errorMessages.String.match; - function matchValidator (v){ - return null != v && '' !== v - ? regExp.test(v) - : true + function matchValidator(v) { + if (!regExp) { + return false; + } + + return null != v && '' !== v ? + regExp.test(v) : + true; } this.validators.push([matchValidator, msg, 'regexp']); diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js index b3413d3..5addfd1 100644 --- a/node_modules/mongoose/lib/schematype.js +++ b/node_modules/mongoose/lib/schematype.js @@ -27,15 +27,17 @@ function SchemaType (path, options, instance) { this._index = null; this.selected; - for (var i in options) if (this[i] && 'function' == typeof this[i]) { - // { unique: true, index: true } - if ('index' == i && this._index) continue; + for (var i in options) { + if (this[i] && 'function' == typeof this[i]) { + // { unique: true, index: true } + if ('index' == i && this._index) continue; - var opts = Array.isArray(options[i]) - ? options[i] - : [options[i]]; + var opts = Array.isArray(options[i]) + ? options[i] + : [options[i]]; - this[i].apply(this, opts); + this[i].apply(this, opts); + } } }; diff --git a/node_modules/mongoose/lib/types/array.js b/node_modules/mongoose/lib/types/array.js index 5f6ee6d..1acec5e 100644 --- a/node_modules/mongoose/lib/types/array.js +++ b/node_modules/mongoose/lib/types/array.js @@ -28,6 +28,12 @@ function MongooseArray (values, path, doc) { var arr = [].concat(values);; arr.__proto__ = MongooseArray.prototype; + Object.defineProperty(arr, '_atomics', { enumerable: false, configurable: true, writable: true }); + Object.defineProperty(arr, 'validators', { enumerable: false, configurable: true, writable: true }); + Object.defineProperty(arr, '_path', {enumerable: false, configurable: true, writable: true }); + Object.defineProperty(arr, '_parent', { enumerable: false, configurable: true, writable: true }); + Object.defineProperty(arr, '_schema', { enumerable: false, configurable: true, writable: true }); + arr._atomics = {}; arr.validators = []; arr._path = path; diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js index e3f6160..fa809bb 100644 --- a/node_modules/mongoose/lib/utils.js +++ b/node_modules/mongoose/lib/utils.js @@ -716,4 +716,3 @@ exports.mergeClone = function(to, from) { } } } - diff --git a/node_modules/mongoose/node_modules/hooks/package.json b/node_modules/mongoose/node_modules/hooks/package.json deleted file mode 100644 index 686c16a..0000000 --- a/node_modules/mongoose/node_modules/hooks/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "hooks", - "description": "Adds pre and post hook functionality to your JavaScript methods.", - "version": "0.2.1", - "keywords": [ - "node", - "hooks", - "middleware", - "pre", - "post" - ], - "homepage": "https://github.com/bnoguchi/hooks-js/", - "repository": { - "type": "git", - "url": "git://github.com/bnoguchi/hooks-js.git" - }, - "author": { - "name": "Brian Noguchi", - "email": "brian.noguchi@gmail.com", - "url": "https://github.com/bnoguchi/" - }, - "main": "./hooks.js", - "directories": { - "lib": "." - }, - "scripts": { - "test": "make test" - }, - "dependencies": {}, - "devDependencies": { - "expresso": ">=0.7.6", - "should": ">=0.2.1", - "underscore": ">=1.1.4" - }, - "engines": { - "node": ">=0.4.0" - }, - "licenses": [ - "MIT" - ], - "optionalDependencies": {}, - "_npmUser": { - "name": "bnoguchi", - "email": "brian.noguchi@gmail.com" - }, - "_id": "hooks@0.2.1", - "_engineSupported": true, - "_npmVersion": "1.1.16", - "_nodeVersion": "v0.6.15", - "_defaultsLoaded": true, - "dist": { - "shasum": "0f591b1b344bdcb3df59773f62fbbaf85bf4028b", - "tarball": "http://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz" - }, - "readme": "hooks\n============\n\nAdd pre and post middleware hooks to your JavaScript methods.\n\n## Installation\n npm install hooks\n\n## Motivation\nSuppose you have a JavaScript object with a `save` method.\n\nIt would be nice to be able to declare code that runs before `save` and after `save`.\nFor example, you might want to run validation code before every `save`,\nand you might want to dispatch a job to a background job queue after `save`.\n\nOne might have an urge to hard code this all into `save`, but that turns out to\ncouple all these pieces of functionality (validation, save, and job creation) more\ntightly than is necessary. For example, what if someone does not want to do background\njob creation after the logical save? \n\nIt is nicer to tack on functionality using what we call `pre` and `post` hooks. These\nare functions that you define and that you direct to execute before or after particular\nmethods.\n\n## Example\nWe can use `hooks` to add validation and background jobs in the following way:\n\n var hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n // Add hooks' methods: `hook`, `pre`, and `post` \n for (var k in hooks) {\n Document[k] = hooks[k];\n }\n\n // Define a new method that is able to invoke pre and post middleware\n Document.hook('save', Document.prototype.save);\n\n // Define a middleware function to be invoked before 'save'\n Document.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n });\n\n // Define a middleware function to be invoked after 'save'\n Document.post('save', function createJob () {\n this.sendToBackgroundQueue();\n });\n\nIf you already have defined `Document.prototype` methods for which you want pres and posts,\nthen you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)`\nor `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]`\nso that it plays well with `hooks`. An equivalent way to implement the previous example is:\n\n```javascript\nvar hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n// Add hooks' methods: `hook`, `pre`, and `post` \nfor (var k in hooks) {\n Document[k] = hooks[k];\n}\n\nDocument.prototype.save = function () {\n // ...\n};\n\n// Define a middleware function to be invoked before 'save'\nDocument.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n});\n\n// Define a middleware function to be invoked after 'save'\nDocument.post('save', function createJob () {\n this.sendToBackgroundQueue();\n});\n```\n\n## Pres and Posts as Middleware\nWe structure pres and posts as middleware to give you maximum flexibility:\n\n1. You can define **multiple** pres (or posts) for a single method.\n2. These pres (or posts) are then executed as a chain of methods.\n3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid.\n\n## Defining multiple pres (or posts)\n`pre` is chainable, so you can define multiple pres via:\n Document.pre('save', function (next, halt) {\n console.log(\"hello\");\n }).pre('save', function (next, halt) {\n console.log(\"world\");\n });\n\nAs soon as one pre finishes executing, the next one will be invoked, and so on.\n\n## Error Handling\nYou can define a default error handler by passing a 2nd function as the 3rd argument to `hook`:\n Document.hook('set', function (path, val) {\n this[path] = val;\n }, function (err) {\n // Handler the error here\n console.error(err);\n });\n\nThen, we can pass errors to this handler from a pre or post middleware function:\n Document.pre('set', function (next, path, val) {\n next(new Error());\n });\n\nIf you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`.\n\nThe default error handler can be over-rided on a per method invocation basis.\n\nIf the main method that you are surrounding with pre and post middleware expects its last argument to be a function\nwith callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default\nerror handler you may have set up.\n \n```javascript\nDocument.hook('save', function (callback) {\n // Save logic goes here\n ...\n});\n\nvar doc = new Document();\ndoc.save( function (err, saved) {\n // We can pass err via `next` in any of our pre or post middleware functions\n if (err) console.error(err);\n \n // Rest of callback logic follows ...\n});\n```\n\n## Mutating Arguments via Middleware\n`pre` and `post` middleware can also accept the intended arguments for the method\nthey augment. This is useful if you want to mutate the arguments before passing\nthem along to the next middleware and eventually pass a mutated arguments list to\nthe main method itself.\n\nAs a simple example, let's define a method `set` that just sets a key, value pair.\nIf we want to namespace the key, we can do so by adding a `pre` middleware hook\nthat runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`:\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n next('namespace-' + key, val);\n });\n var doc = new Document();\n doc.set('hello', 'world');\n console.log(doc.hello); // undefined\n console.log(doc['namespace-hello']); // 'world'\n\nAs you can see above, we pass arguments via `next`.\n\nIf you are not mutating the arguments, then you can pass zero arguments\nto `next`, and the next middleware function will still have access\nto the arguments.\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n // I have access to key and val here\n next(); // We don't need to pass anything to next\n });\n Document.pre('set', function (next, key, val) {\n // And I still have access to the original key and val here\n next();\n });\n\nFinally, you can add arguments that downstream middleware can also see:\n\n // Note that in the definition of `set`, there is no 3rd argument, options\n Document.hook('set', function (key, val) {\n // But...\n var options = arguments[2]; // ...I have access to an options argument\n // because of pre function pre2 (defined below)\n console.log(options); // '{debug: true}'\n this[key] = val;\n });\n Document.pre('set', function pre1 (next, key, val) {\n // I only have access to key and val arguments\n console.log(arguments.length); // 3\n next(key, val, {debug: true});\n });\n Document.pre('set', function pre2 (next, key, val, options) {\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n Document.pre('set', function pre3 (next, key, val, options) {\n // I still have access to key, val, AND the options argument introduced via the preceding middleware\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n \n var doc = new Document()\n doc.set('hey', 'there');\n\n## Parallel `pre` middleware\n\nAll middleware up to this point has been \"serial\" middleware -- i.e., middleware whose logic\nis executed as a serial chain.\n\nSome scenarios call for parallel middleware -- i.e., middleware that can wait for several\nasynchronous services at once to respond.\n\nFor instance, you may only want to save a Document only after you have checked\nthat the Document is valid according to two different remote services.\n\nWe accomplish asynchronous middleware by adding a second kind of flow control callback\n(the only flow control callback so far has been `next`), called `done`.\n\n- `next` passes control to the next middleware in the chain\n- `done` keeps track of how many parallel middleware have invoked `done` and passes\n control to the target method when ALL parallel middleware have invoked `done`. If\n you pass an `Error` to `done`, then the error is handled, and the main method that is\n wrapped by pres and posts will not get invoked.\n\nWe declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre`\ndefinition method.\n\nWe illustrate via the parallel validation example mentioned above:\n\n Document.hook('save', function targetFn (callback) {\n // Save logic goes here\n // ...\n // This only gets run once the two `done`s are both invoked via preOne and preTwo.\n });\n\n // true marks this as parallel middleware\n Document.pre('save', true, function preOne (next, doneOne, callback) {\n remoteServiceOne.validate(this.serialize(), function (err, isValid) {\n // The code in here will probably be run after the `next` below this block\n // and could possibly be run after the console.log(\"Hola\") in `preTwo\n if (err) return doneOne(err);\n if (isValid) doneOne();\n });\n next(); // Pass control to the next middleware\n });\n \n // We will suppose that we need 2 different remote services to validate our document\n Document.pre('save', true, function preTwo (next, doneTwo, callback) {\n remoteServiceTwo.validate(this.serialize(), function (err, isValid) {\n if (err) return doneTwo(err);\n if (isValid) doneTwo();\n });\n next();\n });\n \n // While preOne and preTwo are parallel, preThree is a serial pre middleware\n Document.pre('save', function preThree (next, callback) {\n next();\n });\n \n var doc = new Document();\n doc.save( function (err, doc) {\n // Do stuff with the saved doc here...\n });\n\nIn the above example, flow control may happen in the following way:\n\n(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn\n\nSo what's happening is that:\n\n1. You call `doc.save(...)`\n2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware.\n3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware.\n4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services.\n5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo.\n6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne.\n7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic).\n\n## Removing Pres\n\nYou can remove a particular pre associated with a hook:\n\n Document.pre('set', someFn);\n Document.removePre('set', someFn);\n\nAnd you can also remove all pres associated with a hook:\n Document.removePre('set'); // Removes all declared `pre`s on the hook 'set'\n\n## Tests\nTo run the tests:\n make test\n\n### Contributors\n- [Brian Noguchi](https://github.com/bnoguchi)\n\n### License\nMIT License\n\n---\n### Author\nBrian Noguchi\n", - "maintainers": [ - { - "name": "bnoguchi", - "email": "brian.noguchi@gmail.com" - } - ], - "_shasum": "0f591b1b344bdcb3df59773f62fbbaf85bf4028b", - "_resolved": "https://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz", - "_from": "hooks@0.2.1" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h deleted file mode 100644 index 85dd275..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_pre_12_inl.h +++ /dev/null @@ -1,268 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ -#define NAN_IMPLEMENTATION_PRE_12_INL_H_ - -#include - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# include -# pragma warning( default : 4530 ) -#else -# include -# include -#endif - -//============================================================================== -// node v0.10 implementation -//============================================================================== - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(value)->ToBoolean(); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = v8::Local::New(ctx); - ctx.Dispose(); - return lctx; -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return Factory::New( callback - , data - , v8::Handle() - )->GetFunction(); -} - - -//=== FunctionTemplate ========================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find - // a way. Have at it though... - return v8::FunctionTemplate::New( callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New(value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - return v8::Script::New(source); -} -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - return v8::Script::New(source, const_cast(&origin)); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::New( value.data(), static_cast(value.size())); -} - -inline -void -widenString(std::vector *ws, const uint8_t *s, int l = -1) { - size_t len = static_cast(l); - if (l < 0) { - len = strlen(reinterpret_cast(s)); - } - assert(len <= INT_MAX && "string too long"); - ws->resize(len); - std::copy(s, s + len, ws->begin()); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - std::vector wideString; - widenString(&wideString, value, length); - if (wideString.size() == 0) { - return v8::String::Empty(); - } else { - return v8::String::New(&wideString.front() - , static_cast(wideString.size())); - } -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(value); -} - -Factory::return_t -Factory::New(v8::String::ExternalAsciiStringResource * value) { - return v8::String::NewExternal(value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(p); -} - -#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json deleted file mode 100644 index 1a37609..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/package.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "name": "nan", - "version": "1.7.0", - "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", - "main": "include_dirs.js", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/nan.git" - }, - "scripts": { - "test": "tap --gc test/js/*-test.js", - "rebuild-tests": "pangyp rebuild --directory test" - }, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "Benjamin Byholm", - "email": "bbyholm@abo.fi", - "url": "https://github.com/kkoopa/" - }, - { - "name": "Trevor Norris", - "email": "trev.norris@gmail.com", - "url": "https://github.com/trevnorris" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "https://github.com/TooTallNate" - }, - { - "name": "Brett Lawson", - "email": "brett19@gmail.com", - "url": "https://github.com/brett19" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl", - "url": "https://github.com/bnoordhuis" - }, - { - "name": "David Siegel", - "email": "david@artcom.de", - "url": "https://github.com/agnat" - } - ], - "devDependencies": { - "bindings": "~1.2.1", - "node-gyp": "~1.0.2", - "pangyp": "~2.0.1", - "tap": "~0.5.0", - "xtend": "~4.0.0" - }, - "license": "MIT", - "gitHead": "550efb5dde5cb6bf79db87ab48dce850e56e971a", - "bugs": { - "url": "https://github.com/rvagg/nan/issues" - }, - "homepage": "https://github.com/rvagg/nan", - "_id": "nan@1.7.0", - "_shasum": "755b997404e83cbe7bc08bc3c5c56291bce87438", - "_from": "nan@1.7.0", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - }, - "maintainers": [ - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - } - ], - "dist": { - "shasum": "755b997404e83cbe7bc08bc3c5c56291bce87438", - "tarball": "http://registry.npmjs.org/nan/-/nan-1.7.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/nan/-/nan-1.7.0.tgz" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc deleted file mode 100644 index 47971da..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc +++ /dev/null @@ -1,30 +0,0 @@ -## DNT config file -## see https://github.com/rvagg/dnt - -NODE_VERSIONS="\ - master \ - v0.11.13 \ - v0.10.30 \ - v0.10.29 \ - v0.10.28 \ - v0.10.26 \ - v0.10.25 \ - v0.10.24 \ - v0.10.23 \ - v0.10.22 \ - v0.10.21 \ - v0.10.20 \ - v0.10.19 \ - v0.8.28 \ - v0.8.27 \ - v0.8.26 \ - v0.8.24 \ -" -OUTPUT_PREFIX="nan-" -TEST_CMD=" \ - cd /dnt/ && \ - npm install && \ - node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ - node_modules/.bin/tap --gc test/js/*-test.js \ -" - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md deleted file mode 100644 index de0ac02..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,265 +0,0 @@ -# NAN ChangeLog - -**Version 1.6.2: current Node unstable: 0.11.16, Node stable: 0.10.36, io.js: 1.1.0** - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md deleted file mode 100644 index 95c2eb5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2015 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -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. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml deleted file mode 100644 index 1777107..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml +++ /dev/null @@ -1,37 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -# Test against these versions of Io.js and Node.js. -environment: - matrix: - # node.js - - nodejs_version: "0.8" - - nodejs_version: "0.10" - - nodejs_version: "0.11" - # io.js - - nodejs_version: "1" - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node 0.STABLE.latest - - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} - - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} - - IF NOT %nodejs_version% == 1 npm -g install npm - - IF NOT %nodejs_version% == 1 set PATH=%APPDATA%\npm;%PATH% - # Typical npm stuff. - - npm install - - IF %nodejs_version% == 0.8 node node_modules\node-gyp\bin\node-gyp.js rebuild --directory test - - IF NOT %nodejs_version% == 0.8 npm run rebuild-tests - -# Post-install test scripts. -test_script: - # Output useful info for debugging. - - node --version - - npm --version - # run tests - - npm test - -# Don't actually build. -build: off - -# Set build version format here instead of in the admin panel. -version: "{build}" diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js deleted file mode 100644 index 4f1dfb4..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js +++ /dev/null @@ -1 +0,0 @@ -console.log(require('path').relative('.', __dirname)); diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h deleted file mode 100644 index e95a3b3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h +++ /dev/null @@ -1,2174 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - David Siegel - * - * MIT License - * - * Version 1.6.2: current Node unstable: 0.11.16, Node stable: 0.10.36, io.js: 1.1.0 - * - * See https://github.com/rvagg/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H_ -#define NAN_H_ - -#include -#include -#include -#include -#include -#include -#include -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -#if defined(__GNUC__) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) && !(defined(DEBUG) && DEBUG) -# define NAN_INLINE __forceinline -#else -# define NAN_INLINE inline -#endif - -#if defined(__GNUC__) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __declspec(deprecated) -#else -# define NAN_DEPRECATED -#endif - -#if (NODE_MODULE_VERSION < 12) -typedef v8::InvocationCallback NanFunctionCallback; -typedef v8::Script NanUnboundScript; -typedef v8::Script NanBoundScript; -#else -typedef v8::FunctionCallback NanFunctionCallback; -typedef v8::UnboundScript NanUnboundScript; -typedef v8::Script NanBoundScript; -#endif - -#if (NODE_MODULE_VERSION < 42) -typedef v8::String::ExternalAsciiStringResource - NanExternalOneByteStringResource; -#else // io.js v1.0.0 -typedef v8::String::ExternalOneByteStringResource - NanExternalOneByteStringResource; -#endif - -#include "nan_new.h" // NOLINT(build/include) - -// uv helpers -#ifdef UV_VERSION_MAJOR -#ifndef UV_VERSION_PATCH -#define UV_VERSION_PATCH 0 -#endif -#define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) -#else -#define NAUV_UVVERSION 0x000b00 -#endif - - -#if NAUV_UVVERSION < 0x000b17 -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async, int) -#else -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async) -#endif - -// some generic helpers - -template NAN_INLINE bool NanSetPointerSafe( - T *var - , T val -) { - if (var) { - *var = val; - return true; - } else { - return false; - } -} - -template NAN_INLINE T NanGetPointerSafe( - T *var - , T fallback = reinterpret_cast(0) -) { - if (var) { - return *var; - } else { - return fallback; - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt, bool def -) { - if (def) { - return optionsObj.IsEmpty() - || !optionsObj->Has(opt) - || optionsObj->Get(opt)->BooleanValue(); - } else { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->BooleanValue(); - } -} - -NAN_INLINE bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt -) { - return NanBooleanOptionValue(optionsObj, opt, false); -} - -NAN_INLINE uint32_t NanUInt32OptionValue( - v8::Local optionsObj - , v8::Handle opt - , uint32_t def -) { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->IsNumber() - ? optionsObj->Get(opt)->Uint32Value() - : def; -} - -template -v8::Local NanNew(v8::Handle); - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Handle val) { - return NanNew(val); -} - -template -NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { - return val; -} - -/* io.js 1.0 */ -#if NODE_MODULE_VERSION >= 42 || NODE_VERSION_AT_LEAST(0, 11, 15) - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::Isolate::GetCurrent()->SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::Isolate::GetCurrent()->LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::Isolate::GetCurrent()->ContextDisposedNotification(); - } -#else - NAN_INLINE - void NanSetCounterFunction(v8::CounterLookupCallback cb) { - v8::V8::SetCounterFunction(cb); - } - - NAN_INLINE - void NanSetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::V8::SetCreateHistogramFunction(cb); - } - - NAN_INLINE - void NanSetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::V8::SetAddHistogramSampleFunction(cb); - } - - NAN_INLINE bool NanIdleNotification(int idle_time_in_ms) { - return v8::V8::IdleNotification(idle_time_in_ms); - } - - NAN_INLINE void NanLowMemoryNotification() { - v8::V8::LowMemoryNotification(); - } - - NAN_INLINE void NanContextDisposedNotification() { - v8::V8::ContextDisposedNotification(); - } -#endif - -#if (NODE_MODULE_VERSION > 0x000B) -// Node 0.11+ (0.11.12 and below won't compile with these) - -# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE void - -# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE void - -# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_DELETER_ARGS \ - _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE void - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE void - -# define _NAN_INDEX_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE void - -# define _NAN_INDEX_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE void - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void - -# define _NAN_INDEX_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE void - -# define _NAN_INDEX_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE void - -# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) -# define NanEscapableScope() \ - v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) - -# define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) -# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) -# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) -# define NanReturnUndefined() return -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnNull() return args.GetReturnValue().SetNull() -# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() - -# define NanObjectWrapHandle(obj) obj->handle() - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast( - v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(v8::Isolate::GetCurrent(), name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Isolate::GetCurrent()->GetCurrentContext(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetAlignedPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetAlignedPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::Isolate::GCEpilogueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); - } - - NAN_INLINE void NanAddGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); - } - - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::Isolate::GCPrologueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); - } - - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return NanNew(data, length); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , const v8::Persistent& obj) { - handle.Reset(v8::Isolate::GetCurrent(), obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData& data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param), callback(cb) { - NanAssignPersistent(persistent, handle); - } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Reset(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakCallbackDispatcher( - const v8::WeakCallbackData > &data) { - _NanWeakCallbackInfo *info = data.GetParameter(); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); - } - -template -NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); - return cbinfo; -} - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE void NanThrowError(v8::Handle error) { - NanScope(); - v8::Isolate::GetCurrent()->ThrowException(error); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(NanNew(msg)); - v8::Local obj = err.As(); - obj->Set(NanNew("code"), NanNew(errorNumber)); - return err; - } - - NAN_INLINE void NanThrowError( - const char *msg - , const int errorNumber - ) { - NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE void NanThrowTypeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE void NanThrowRangeError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle - ) { - handle.Reset(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::smalloc::FreeCallback callback - , void *hint - ) { - return node::Buffer::New( - v8::Isolate::GetCurrent(), data, length, callback, hint); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return node::Buffer::New(v8::Isolate::GetCurrent(), size); - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return NanNew(function_template)->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return v8::Local::New( - isolate - , v8::Context::New(isolate, extensions, tmpl, obj) - ); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::ScriptCompiler::Source source(s, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - v8::ScriptCompiler::Source source(s); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->BindToCurrentContext()->Run(); - } - - NAN_INLINE v8::Local NanRunScript( - v8::Handle script - ) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv)); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { - return NanNew(node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv)); - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(0, data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData(0)); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteOneByte(reinterpret_cast(buf)); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#else -// Node 0.8 and 0.10 - -# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE v8::Handle - -# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle - - NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( - const char* data, int length = -1) { - return v8::String::NewSymbol(data, length); - } - -# define NanScope() v8::HandleScope scope -# define NanEscapableScope() v8::HandleScope scope -# define NanEscapeScope(val) scope.Close(val) -# define NanLocker() v8::Locker locker -# define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) -# define NanReturnHolder() NanReturnValue(args.Holder()) -# define NanReturnThis() NanReturnValue(args.This()) -# define NanReturnUndefined() return v8::Undefined() -# define NanReturnNull() return v8::Null() -# define NanReturnEmptyString() return v8::String::Empty() -# define NanObjectWrapHandle(obj) v8::Local::New(obj->handle_) - - NAN_INLINE v8::Local NanUndefined() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Undefined())); - } - - NAN_INLINE v8::Local NanNull() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::Null())); - } - - NAN_INLINE v8::Local NanTrue() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::True())); - } - - NAN_INLINE v8::Local NanFalse() { - NanEscapableScope(); - return NanEscapeScope(NanNew(v8::False())); - } - - NAN_INLINE int NanAdjustExternalMemory(int bc) { - return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , const char *name - , v8::Handle value) { - templ->Set(name, value); - } - - NAN_INLINE void NanSetTemplate( - v8::Handle templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - NAN_INLINE v8::Local NanGetCurrentContext() { - return v8::Context::GetCurrent(); - } - - NAN_INLINE void* NanGetInternalFieldPointer( - v8::Handle object - , int index) { - return object->GetPointerFromInternalField(index); - } - - NAN_INLINE void NanSetInternalFieldPointer( - v8::Handle object - , int index - , void* value) { - object->SetPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::GCType type, v8::GCCallbackFlags flags) - - NAN_INLINE void NanAddGCEpilogueCallback( - v8::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCEpilogueCallback( - v8::GCEpilogueCallback callback) { - v8::V8::RemoveGCEpilogueCallback(callback); - } - NAN_INLINE void NanAddGCPrologueCallback( - v8::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCPrologueCallback(callback, gc_type_filter); - } - NAN_INLINE void NanRemoveGCPrologueCallback( - v8::GCPrologueCallback callback) { - v8::V8::RemoveGCPrologueCallback(callback); - } - NAN_INLINE void NanGetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::V8::GetHeapStatistics(heap_statistics); - } - - template - NAN_INLINE void NanAssignPersistent( - v8::Persistent& handle - , v8::Handle obj) { - handle.Dispose(); - handle = v8::Persistent::New(obj); - } - - template - class _NanWeakCallbackData; - - template - struct _NanWeakCallbackInfo { - typedef void (*Callback)(const _NanWeakCallbackData &data); - NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) - : parameter(param) - , callback(cb) - , persistent(v8::Persistent::New(handle)) { } - - NAN_INLINE ~_NanWeakCallbackInfo() { - persistent.Dispose(); - persistent.Clear(); - } - - P* const parameter; - Callback const callback; - v8::Persistent persistent; - }; - - template - class _NanWeakCallbackData { - public: - NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) - : info_(info) { } - - NAN_INLINE v8::Local GetValue() const { - return NanNew(info_->persistent); - } - - NAN_INLINE P* GetParameter() const { return info_->parameter; } - - NAN_INLINE bool IsNearDeath() const { - return info_->persistent.IsNearDeath(); - } - - NAN_INLINE void Revive() const; - - NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { - return info_; - } - - NAN_DEPRECATED NAN_INLINE void Dispose() const { - } - - private: - _NanWeakCallbackInfo* info_; - }; - - template - static void _NanWeakPersistentDispatcher( - v8::Persistent object, void *data) { - _NanWeakCallbackInfo* info = - static_cast<_NanWeakCallbackInfo*>(data); - _NanWeakCallbackData wcbd(info); - info->callback(wcbd); - if (wcbd.IsNearDeath()) { - delete wcbd.GetCallbackInfo(); - } - } - - template - NAN_INLINE void _NanWeakCallbackData::Revive() const { - info_->persistent.MakeWeak( - info_ - , &_NanWeakPersistentDispatcher); - } - - template - NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( - v8::Handle handle - , P* parameter - , typename _NanWeakCallbackInfo::Callback callback) { - _NanWeakCallbackInfo *cbinfo = - new _NanWeakCallbackInfo(handle, parameter, callback); - cbinfo->persistent.MakeWeak( - cbinfo - , &_NanWeakPersistentDispatcher); - return cbinfo; - } - -# define NAN_WEAK_CALLBACK(name) \ - template \ - static void name(const _NanWeakCallbackData &data) - -# define _NAN_ERROR(fun, errmsg) \ - fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - return v8::Local::New( \ - v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ - } while (0); - - NAN_INLINE v8::Local NanError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError(const char* errmsg) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - NAN_INLINE v8::Local NanThrowError( - v8::Handle error - ) { - NanScope(); - return v8::Local::New(v8::ThrowException(error)); - } - - NAN_INLINE v8::Local NanError( - const char *msg - , const int errorNumber - ) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - NAN_INLINE v8::Local NanThrowError( - const char *msg - , const int errorNumber - ) { - return NanThrowError(NanError(msg, errorNumber)); - } - - NAN_INLINE v8::Local NanTypeError(const char* errmsg) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowTypeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - NAN_INLINE v8::Local NanRangeError( - const char* errmsg - ) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - NAN_INLINE v8::Local NanThrowRangeError( - const char* errmsg - ) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template - NAN_INLINE void NanDisposePersistent( - v8::Persistent &handle) { // NOLINT(runtime/references) - handle.Dispose(); - handle.Clear(); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - ) { - return NanNew( - node::Buffer::New(data, length, callback, hint)->handle_); - } - - NAN_INLINE v8::Local NanNewBufferHandle ( - const char *data - , uint32_t size - ) { -#if NODE_MODULE_VERSION >= 0x000B - return NanNew(node::Buffer::New(data, size)->handle_); -#else - return NanNew( - node::Buffer::New(const_cast(data), size)->handle_); -#endif - } - - NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { - return NanNew(node::Buffer::New(size)->handle_); - } - - NAN_INLINE void FreeData(char *data, void *hint) { - delete[] data; - } - - NAN_INLINE v8::Local NanBufferUse( - char* data - , uint32_t size - ) { - return NanNew( - node::Buffer::New(data, size, FreeData, NULL)->handle_); - } - - NAN_INLINE bool NanHasInstance( - const v8::Persistent& function_template - , v8::Handle value - ) { - return function_template->HasInstance(value); - } - - NAN_DEPRECATED NAN_INLINE v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - ) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = NanNew(ctx); - ctx.Dispose(); - return lctx; - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - return v8::Script::Compile(s, const_cast(&origin)); - } - - NAN_INLINE v8::Local NanCompileScript( - v8::Local s - ) { - return v8::Script::Compile(s); - } - - NAN_INLINE v8::Local NanRunScript(v8::Handle script) { - return script->Run(); - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle func - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, func, argc, argv)); -# else - v8::TryCatch try_catch; - v8::Local result = func->Call(target, argc, argv); - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - return result; -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , v8::Handle symbol - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, symbol, argc, argv)); -# else - v8::Local callback = target->Get(symbol).As(); - return NanMakeCallback(target, callback, argc, argv); -# endif - } - - NAN_INLINE v8::Local NanMakeCallback( - v8::Handle target - , const char* method - , int argc - , v8::Handle* argv) { -# if NODE_VERSION_AT_LEAST(0, 8, 0) - return NanNew(node::MakeCallback(target, method, argc, argv)); -# else - return NanMakeCallback(target, NanNew(method), argc, argv); -# endif - } - - template - NAN_INLINE void NanSetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(data); - } - - template - NAN_INLINE T *NanGetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData()); - } - - class NanAsciiString { - public: - NAN_INLINE explicit NanAsciiString(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new char[size + 1]; - size = toStr->WriteAscii(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanAsciiString() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanAsciiString(const NanAsciiString&); - void operator=(const NanAsciiString&); - - char *buf; - int size; - }; - - class NanUtf8String { - public: - NAN_INLINE explicit NanUtf8String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Utf8Length(); - buf = new char[size + 1]; - toStr->WriteUtf8(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE char* operator*() { return buf; } - NAN_INLINE const char* operator*() const { return buf; } - - NAN_INLINE ~NanUtf8String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUtf8String(const NanUtf8String&); - void operator=(const NanUtf8String&); - - char *buf; - int size; - }; - - class NanUcs2String { - public: - NAN_INLINE explicit NanUcs2String(v8::Handle from) { - v8::Local toStr = from->ToString(); - size = toStr->Length(); - buf = new uint16_t[size + 1]; - toStr->Write(buf); - } - - NAN_DEPRECATED NAN_INLINE int Size() const { - return size; - } - - NAN_INLINE int length() const { - return size; - } - - NAN_INLINE uint16_t* operator*() { return buf; } - NAN_INLINE const uint16_t* operator*() const { return buf; } - - NAN_INLINE ~NanUcs2String() { - delete[] buf; - } - - private: - // disallow copying and assigning - NanUcs2String(const NanUcs2String&); - void operator=(const NanUcs2String&); - - uint16_t *buf; - int size; - }; - -#endif // NODE_MODULE_VERSION - -typedef void (*NanFreeCallback)(char *data, void *hint); - -#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) -#define NAN_GETTER(name) \ - _NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_GETTER_ARGS) -#define NAN_SETTER(name) \ - _NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -#define NAN_PROPERTY_GETTER(name) \ - _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -#define NAN_PROPERTY_SETTER(name) \ - _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -#define NAN_PROPERTY_ENUMERATOR(name) \ - _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) -#define NAN_PROPERTY_DELETER(name) \ - _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -#define NAN_PROPERTY_QUERY(name) \ - _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_QUERY_ARGS) -# define NAN_INDEX_GETTER(name) \ - _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) -#define NAN_INDEX_SETTER(name) \ - _NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -#define NAN_INDEX_ENUMERATOR(name) \ - _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) -#define NAN_INDEX_DELETER(name) \ - _NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -#define NAN_INDEX_QUERY(name) \ - _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) - -class NanCallback { - public: - NanCallback() { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - } - - explicit NanCallback(const v8::Handle &fn) { - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(handle, obj); - SetFunction(fn); - } - - ~NanCallback() { - if (handle.IsEmpty()) return; - NanDisposePersistent(handle); - } - - NAN_INLINE void SetFunction(const v8::Handle &fn) { - NanScope(); - NanNew(handle)->Set(kCallbackIndex, fn); - } - - NAN_INLINE v8::Local GetFunction() const { - NanEscapableScope(); - return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) - .As()); - } - - NAN_INLINE bool IsEmpty() const { - NanScope(); - return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); - } - - v8::Handle Call(int argc, v8::Handle argv[]) const { - NanEscapableScope(); -#if (NODE_MODULE_VERSION > 0x000B) // 0.11.12+ - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::Local callback = NanNew(handle)-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - isolate - , isolate->GetCurrentContext()->Global() - , callback - , argc - , argv - )); -#else -#if NODE_VERSION_AT_LEAST(0, 8, 0) - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(node::MakeCallback( - v8::Context::GetCurrent()->Global() - , callback - , argc - , argv - )); -#else - v8::Local callback = handle-> - Get(kCallbackIndex).As(); - return NanEscapeScope(NanMakeCallback( - v8::Context::GetCurrent()->Global(), callback, argc, argv)); -#endif -#endif - } - - private: - v8::Persistent handle; - static const uint32_t kCallbackIndex = 0; -}; - -/* abstract */ class NanAsyncWorker { - public: - explicit NanAsyncWorker(NanCallback *callback_) - : callback(callback_), errmsg_(NULL) { - request.data = this; - - NanScope(); - v8::Local obj = NanNew(); - NanAssignPersistent(persistentHandle, obj); - } - - virtual ~NanAsyncWorker() { - NanScope(); - - if (!persistentHandle.IsEmpty()) - NanDisposePersistent(persistentHandle); - if (callback) - delete callback; - if (errmsg_) - delete[] errmsg_; - } - - virtual void WorkComplete() { - NanScope(); - - if (errmsg_ == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - NAN_INLINE void SaveToPersistent( - const char *key, const v8::Local &obj) { - v8::Local handle = NanNew(persistentHandle); - handle->Set(NanNew(key), obj); - } - - v8::Local GetFromPersistent(const char *key) const { - NanEscapableScope(); - v8::Local handle = NanNew(persistentHandle); - return NanEscapeScope(handle->Get(NanNew(key)).As()); - } - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy() { - delete this; - } - - protected: - v8::Persistent persistentHandle; - NanCallback *callback; - - virtual void HandleOKCallback() { - callback->Call(0, NULL); - } - - virtual void HandleErrorCallback() { - NanScope(); - - v8::Local argv[] = { - v8::Exception::Error(NanNew(ErrorMessage())) - }; - callback->Call(1, argv); - } - - void SetErrorMessage(const char *msg) { - if (errmsg_) { - delete[] errmsg_; - } - - size_t size = strlen(msg) + 1; - errmsg_ = new char[size]; - memcpy(errmsg_, msg, size); - } - - const char* ErrorMessage() const { - return errmsg_; - } - - private: - char *errmsg_; -}; - -/* abstract */ class NanAsyncProgressWorker : public NanAsyncWorker { - public: - explicit NanAsyncProgressWorker(NanCallback *callback_) - : NanAsyncWorker(callback_), asyncdata_(NULL), asyncsize_(0) { - async = new uv_async_t; - uv_async_init( - uv_default_loop() - , async - , AsyncProgress_ - ); - async->data = this; - - uv_mutex_init(&async_lock); - } - - virtual ~NanAsyncProgressWorker() { - uv_mutex_destroy(&async_lock); - - if (asyncdata_) { - delete[] asyncdata_; - } - } - - void WorkProgress() { - uv_mutex_lock(&async_lock); - char *data = asyncdata_; - size_t size = asyncsize_; - asyncdata_ = NULL; - uv_mutex_unlock(&async_lock); - - // Dont send progress events after we've already completed. - if (callback) { - HandleProgressCallback(data, size); - } - delete[] data; - } - - class ExecutionProgress { - friend class NanAsyncProgressWorker; - public: - // You could do fancy generics with templates here. - void Send(const char* data, size_t size) const { - that_->SendProgress_(data, size); - } - - private: - explicit ExecutionProgress(NanAsyncProgressWorker* that) : that_(that) {} - // Prohibit copying and assignment. - ExecutionProgress(const ExecutionProgress&); - void operator=(const ExecutionProgress&); - #if __cplusplus >= 201103L - // Prohibit C++11 move semantics. - ExecutionProgress(ExecutionProgress&&) = delete; - void operator=(ExecutionProgress&&) = delete; - #endif - NanAsyncProgressWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const char *data, size_t size) = 0; - - virtual void Destroy() { - uv_close(reinterpret_cast(async), AsyncClose_); - } - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - void SendProgress_(const char *data, size_t size) { - char *new_data = new char[size]; - memcpy(new_data, data, size); - - uv_mutex_lock(&async_lock); - char *old_data = asyncdata_; - asyncdata_ = new_data; - asyncsize_ = size; - uv_mutex_unlock(&async_lock); - - if (old_data) { - delete[] old_data; - } - uv_async_send(async); - } - - NAN_INLINE static NAUV_WORK_CB(AsyncProgress_) { - NanAsyncProgressWorker *worker = - static_cast(async->data); - worker->WorkProgress(); - } - - NAN_INLINE static void AsyncClose_(uv_handle_t* handle) { - NanAsyncProgressWorker *worker = - static_cast(handle->data); - delete reinterpret_cast(handle); - delete worker; - } - - uv_async_t *async; - uv_mutex_t async_lock; - char *asyncdata_; - size_t asyncsize_; -}; - -NAN_INLINE void NanAsyncExecute (uv_work_t* req) { - NanAsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { - NanAsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - worker->Destroy(); -} - -NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { - uv_queue_work( - uv_default_loop() - , &worker->request - , NanAsyncExecute - , (uv_after_work_cb)NanAsyncExecuteComplete - ); -} - -//// Base 64 //// - -#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - -// Doesn't check for padding at the end. Can be 1-2 bytes over. -NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { - size_t remainder = size % 4; - - size = (size / 4) * 3; - if (remainder) { - if (size == 0 && remainder == 1) { - // special case: 1-byte input cannot be decoded - size = 0; - } else { - // non-padded input, add 1 or 2 extra bytes - size += 1 + (remainder == 3); - } - } - - return size; -} - -template -NAN_INLINE size_t _nan_base64_decoded_size( - const T* src - , size_t size -) { - if (size == 0) - return 0; - - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; - - return _nan_base64_decoded_size_fast(size); -} - -// supports regular and URL-safe base64 -static const int _nan_unbase64_table[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 - , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 - , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 - , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 - , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 - , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] - -template static size_t _nan_base64_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - char* dst = buf; - char* dstEnd = buf + len; - const T* srcEnd = src + srcLen; - - while (src < srcEnd && dst < dstEnd) { - ptrdiff_t remaining = srcEnd - src; - char a, b, c, d; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining == 0 || *src == '=') break; - a = _nan_unbase64(*src++); - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 1 || *src == '=') break; - b = _nan_unbase64(*src++); - - *dst++ = (a << 2) | ((b & 0x30) >> 4); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 2 || *src == '=') break; - c = _nan_unbase64(*src++); - - *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 3 || *src == '=') break; - d = _nan_unbase64(*src++); - - *dst++ = ((c & 0x03) << 6) | (d & 0x3F); - } - - return dst - buf; -} - -//// HEX //// - -template unsigned _nan_hex2bin(T c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - return static_cast(-1); -} - -template static size_t _nan_hex_decode( - char* buf - , size_t len - , const T* src - , const size_t srcLen -) { - size_t i; - for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = _nan_hex2bin(src[i * 2 + 0]); - unsigned b = _nan_hex2bin(src[i * 2 + 1]); - if (!~a || !~b) return i; - buf[i] = a * 16 + b; - } - - return i; -} - -namespace NanIntern { - -inline -NanExternalOneByteStringResource const* -GetExternalResource(v8::Local str) { -#if NODE_MODULE_VERSION < 42 - return str->GetExternalAsciiStringResource(); -#else // io.js v1.0.0 - return str->GetExternalOneByteStringResource(); -#endif -} - -inline -bool -IsExternal(v8::Local str) { -#if NODE_MODULE_VERSION < 42 - return str->IsExternalAscii(); -#else // io.js v1.0.0 - return str->IsExternalOneByte(); -#endif -} - -} // end of namespace NanIntern - -static bool _NanGetExternalParts( - v8::Handle val - , const char** data - , size_t* len -) { - if (node::Buffer::HasInstance(val)) { - *data = node::Buffer::Data(val.As()); - *len = node::Buffer::Length(val.As()); - return true; - } - - assert(val->IsString()); - v8::Local str = NanNew(val.As()); - - if (NanIntern::IsExternal(str)) { - const NanExternalOneByteStringResource* ext; - ext = NanIntern::GetExternalResource(str); - *data = ext->data(); - *len = ext->length(); - return true; - } - - if (str->IsExternal()) { - const v8::String::ExternalStringResource* ext; - ext = str->GetExternalStringResource(); - *data = reinterpret_cast(ext->data()); - *len = ext->length(); - return true; - } - - return false; -} - -namespace Nan { - enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -} - -#if !NODE_VERSION_AT_LEAST(0, 10, 0) -# include "nan_string_bytes.h" // NOLINT(build/include) -#endif - -NAN_INLINE v8::Local NanEncode( - const void *buf, size_t len, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION >= 42) - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::encoding node_enc = static_cast(encoding); - - if (encoding == Nan::UCS2) { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len / 2); - } else { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len - , node_enc); - } -#elif (NODE_MODULE_VERSION > 0x000B) - return node::Encode( - v8::Isolate::GetCurrent() - , buf, len - , static_cast(encoding)); -#else -# if NODE_VERSION_AT_LEAST(0, 10, 0) - return node::Encode(buf, len, static_cast(encoding)); -# else - return NanIntern::Encode(reinterpret_cast(buf), len, encoding); -# endif -#endif -} - -NAN_INLINE ssize_t NanDecodeBytes( - v8::Handle val, enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > 0x000B) - return node::DecodeBytes( - v8::Isolate::GetCurrent() - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < 0x000B) - if (encoding == Nan::BUFFER) { - return node::DecodeBytes(val, node::BINARY); - } -# endif - return node::DecodeBytes(val, static_cast(encoding)); -#endif -} - -NAN_INLINE ssize_t NanDecodeWrite( - char *buf - , size_t len - , v8::Handle val - , enum Nan::Encoding encoding = Nan::BINARY) { -#if (NODE_MODULE_VERSION > 0x000B) - return node::DecodeWrite( - v8::Isolate::GetCurrent() - , buf - , len - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < 0x000B) - if (encoding == Nan::BUFFER) { - return node::DecodeWrite(buf, len, val, node::BINARY); - } -# endif - return node::DecodeWrite( - buf - , len - , val - , static_cast(encoding)); -#endif -} - -/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - NanScope(); - - size_t sz_; - size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); - char *data = NULL; - size_t len; - bool is_extern = _NanGetExternalParts( - from - , const_cast(&data) - , &len); - - if (is_extern && !term_len) { - NanSetPointerSafe(datalen, len); - return data; - } - - v8::Local toStr = from->ToString(); - - char *to = static_cast(buf); - - switch (encoding) { - case Nan::ASCII: -#if NODE_MODULE_VERSION < 0x000C - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); - return to; -#endif - case Nan::BINARY: - case Nan::BUFFER: - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } -#if NODE_MODULE_VERSION < 0x000C - { - uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; - - size_t somelen = toStr->Write(twobytebuf, 0, - static_cast(sz_ + term_len), flags); - - for (size_t i = 0; i < sz_ + term_len && i < somelen + term_len; i++) { - unsigned char *b = reinterpret_cast(&twobytebuf[i]); - to[i] = *b; - } - - NanSetPointerSafe(datalen, somelen); - - delete[] twobytebuf; - return to; - } -#else - NanSetPointerSafe( - datalen, - toStr->WriteOneByte( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags)); - return to; -#endif - case Nan::UTF8: - sz_ = toStr->Utf8Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteUtf8(to, static_cast(sz_ + term_len) - , NULL, flags) - - term_len); - return to; - case Nan::BASE64: - { - v8::String::Value value(toStr); - sz_ = _nan_base64_decoded_size(*value, value.length()); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len); - } - NanSetPointerSafe( - datalen - , _nan_base64_decode(to, sz_, *value, value.length())); - if (term_len) { - to[sz_] = '\0'; - } - return to; - } - case Nan::UCS2: - { - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[(sz_ + term_len) * 2]; - } else { - assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); - } - - int bc = 2 * toStr->Write( - reinterpret_cast(to) - , 0 - , static_cast(sz_ + term_len) - , flags); - NanSetPointerSafe(datalen, bc); - return to; - } - case Nan::HEX: - { - v8::String::Value value(toStr); - sz_ = value.length(); - assert(!(sz_ & 1) && "bad hex data"); - if (to == NULL) { - to = new char[sz_ / 2 + term_len]; - } else { - assert(buflen >= sz_ / 2 + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , _nan_hex_decode(to, sz_ / 2, *value, value.length())); - } - if (term_len) { - to[sz_ / 2] = '\0'; - } - return to; - default: - assert(0 && "unknown encoding"); - } - return to; -} - -NAN_DEPRECATED NAN_INLINE void* NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -) { - return _NanRawString(from, encoding, datalen, buf, buflen, flags); -} - - -NAN_DEPRECATED NAN_INLINE char* NanCString( - v8::Handle from - , size_t *datalen - , char *buf = NULL - , size_t buflen = 0 - , int flags = v8::String::NO_OPTIONS -) { - return static_cast( - _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) - ); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value); -} - -NAN_INLINE void NanSetPrototypeTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , const char *name - , v8::Handle value -) { - NanSetTemplate(templ->InstanceTemplate(), name, value); -} - -NAN_INLINE void NanSetInstanceTemplate( - v8::Local templ - , v8::Handle name - , v8::Handle value - , v8::PropertyAttribute attributes -) { - NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); -} - -//=== Export ================================================================== - -inline -void -NanExport(v8::Handle target, const char * name, - NanFunctionCallback f) { - target->Set(NanNew(name), - NanNew(f)->GetFunction()); -} - -//=== Tap Reverse Binding ===================================================== - -struct NanTap { - explicit NanTap(v8::Handle t) : t_() { - NanAssignPersistent(t_, t->ToObject()); - } - - ~NanTap() { NanDisposePersistent(t_); } // not sure if neccessary - - inline void plan(int i) { - v8::Handle arg = NanNew(i); - NanMakeCallback(NanNew(t_), "plan", 1, &arg); - } - - inline void ok(bool isOk, const char * msg = NULL) { - v8::Handle args[2]; - args[0] = NanNew(isOk); - if (msg) args[1] = NanNew(msg); - NanMakeCallback(NanNew(t_), "ok", msg ? 2 : 1, args); - } - - private: - v8::Persistent t_; -}; - -#define NAN_STRINGIZE2(x) #x -#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) -#define NAN_TEST_EXPRESSION(expression) \ - ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression - -#define return_NanValue(v) NanReturnValue(v) -#define return_NanUndefined() NanReturnUndefined() -#define NAN_EXPORT(target, function) NanExport(target, #function, function) - -#endif // NAN_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h deleted file mode 100644 index ff63ec0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h +++ /dev/null @@ -1,262 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_12_INL_H_ -#define NAN_IMPLEMENTATION_12_INL_H_ -//============================================================================== -// node v0.11 implementation -//============================================================================== - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(v8::Isolate::GetCurrent(), length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(v8::Isolate::GetCurrent(), value); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Handle tmpl - , v8::Handle obj) { - return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(v8::Isolate::GetCurrent(), value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data) { - return v8::Function::New( v8::Isolate::GetCurrent() - , callback - , data); -} - -//=== Function Template ======================================================== - -Factory::return_t -Factory::New( NanFunctionCallback callback - , v8::Handle data - , v8::Handle signature) { - return v8::FunctionTemplate::New( v8::Isolate::GetCurrent() - , callback - , data - , signature); -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(v8::Isolate::GetCurrent(), value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New( v8::Isolate::GetCurrent() - , value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(v8::Isolate::GetCurrent(), value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(v8::Isolate::GetCurrent()); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Handle pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), - value.data(), v8::String::kNormalString, static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint8_t * value, int length) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(NanExternalOneByteStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Handle value) { - return v8::StringObject::New(value).As(); -} - -//=== Unbound Script =========================================================== - -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -} // end of namespace NanIntern - -//=== Presistents and Handles ================================================== - -template -inline v8::Local NanNew(v8::Handle h) { - return v8::Local::New(v8::Isolate::GetCurrent(), h); -} - -template -inline v8::Local NanNew(v8::Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h deleted file mode 100644 index 95b6b51..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h +++ /dev/null @@ -1,329 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2015 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_NEW_H_ -#define NAN_NEW_H_ - -#if defined(_MSC_VER) -# pragma warning( disable : 4530 ) -# include -# pragma warning( default : 4530 ) -#else -# include -#endif - -namespace NanIntern { // scnr - -// TODO(agnat): Generalize -template v8::Local To(v8::Handle i); - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInteger(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToInt32(); } - -template <> -inline -v8::Local -To(v8::Handle i) { return i->ToUint32(); } - -template struct FactoryBase { typedef v8::Local return_t; }; - -template struct Factory; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(int length); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(void *value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback - , v8::Handle data = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( NanFunctionCallback callback = NULL - , v8::Handle data = v8::Handle() - , v8::Handle signature = v8::Handle()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template -struct IntegerFactory : FactoryBase { - typedef typename FactoryBase::return_t return_t; - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( - v8::Handle pattern, v8::RegExp::Flags flags); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -template <> -struct Factory : FactoryBase { - typedef v8::Handle FTH; - static inline - return_t - New( FTH receiver = FTH(), int argc = 0, FTH argv[] = NULL ); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(const char *value, int length = -1); - static inline return_t New(const uint16_t *value, int length = -1); - static inline return_t New(std::string const& value); - - static inline return_t New(v8::String::ExternalStringResource * value); - static inline return_t New(NanExternalOneByteStringResource * value); - - // TODO(agnat): Deprecate. - static inline return_t New(const uint8_t * value, int length = -1); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(v8::Handle value); -}; - -} // end of namespace NanIntern - -#if (NODE_MODULE_VERSION >= 12) - -namespace NanIntern { - -template <> -struct Factory : FactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -} // end of namespace NanIntern - -# include "nan_implementation_12_inl.h" - -#else // NODE_MODULE_VERSION >= 12 - -# include "nan_implementation_pre_12_inl.h" - -#endif - -//=== API ====================================================================== - -template -typename NanIntern::Factory::return_t -NanNew() { - return NanIntern::Factory::New(); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0) { - return NanIntern::Factory::New(arg0); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1) { - return NanIntern::Factory::New(arg0, arg1); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2) { - return NanIntern::Factory::New(arg0, arg1, arg2); -} - -template -typename NanIntern::Factory::return_t -NanNew(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { - return NanIntern::Factory::New(arg0, arg1, arg2, arg3); -} - -// Note(agnat): When passing overloaded function pointers to template functions -// as generic arguments the compiler needs help in picking the right overload. -// These two functions handle NanNew and NanNew with -// all argument variations. - -// v8::Function and v8::FunctionTemplate with one or two arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle()) { - return NanIntern::Factory::New(callback, data); -} - -// v8::Function and v8::FunctionTemplate with three arguments -template -typename NanIntern::Factory::return_t -NanNew( NanFunctionCallback callback - , v8::Handle data = v8::Handle() - , A2 a2 = A2()) { - return NanIntern::Factory::New(callback, data, a2); -} - -// Convenience - -template inline v8::Local NanNew(v8::Handle h); -template inline v8::Local NanNew(v8::Persistent const& p); - -inline -NanIntern::Factory::return_t -NanNew(bool value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(int32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(uint32_t value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(double value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(std::string const& value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value, int length) { - return NanNew(value, length); -} - -inline -NanIntern::Factory::return_t -NanNew(const char * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint8_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(const uint16_t * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::String::ExternalStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(NanExternalOneByteStringResource * value) { - return NanNew(value); -} - -inline -NanIntern::Factory::return_t -NanNew(v8::Handle pattern, v8::RegExp::Flags flags) { - return NanNew(pattern, flags); -} - -#endif // NAN_NEW_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h deleted file mode 100644 index 9deecfb..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -#ifndef NAN_STRING_BYTES_H_ -#define NAN_STRING_BYTES_H_ - -// Decodes a v8::Handle or Buffer to a raw char* - -#include -#include -#include -#include // memcpy -#include - -namespace NanIntern { - -using v8::Local; -using v8::Handle; -using v8::Object; -using v8::String; -using v8::Value; - - -//// Base 64 //// - -#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - - - -//// Nan::HEX //// - -static bool contains_non_ascii_slow(const char* buf, size_t len) { - for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) return true; - } - return false; -} - - -static bool contains_non_ascii(const char* src, size_t len) { - if (len < 16) { - return contains_non_ascii_slow(src, len); - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned unaligned = reinterpret_cast(src) & align_mask; - - if (unaligned > 0) { - const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) return true; - src += n; - len -= n; - } - - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = 0x8080808080808080ll; -#else - const uintptr_t mask = 0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) return true; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) return true; - } - - return false; -} - - -static void force_ascii_slow(const char* src, char* dst, size_t len) { - for (size_t i = 0; i < len; ++i) { - dst[i] = src[i] & 0x7f; - } -} - - -static void force_ascii(const char* src, char* dst, size_t len) { - if (len < 16) { - force_ascii_slow(src, dst, len); - return; - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned src_unalign = reinterpret_cast(src) & align_mask; - const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; - - if (src_unalign > 0) { - if (src_unalign == dst_unalign) { - const unsigned unalign = bytes_per_word - src_unalign; - force_ascii_slow(src, dst, unalign); - src += unalign; - dst += unalign; - len -= src_unalign; - } else { - force_ascii_slow(src, dst, len); - return; - } - } - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = ~0x8080808080808080ll; -#else - const uintptr_t mask = ~0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - uintptr_t* dstw = reinterpret_cast(dst); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - dstw[i] = srcw[i] & mask; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - force_ascii_slow(src + offset, dst + offset, remainder); - } -} - - -static size_t base64_encode(const char* src, - size_t slen, - char* dst, - size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= base64_encoded_size(slen) && - "not enough space provided for base64 encode"); - - dlen = base64_encoded_size(slen); - - unsigned a; - unsigned b; - unsigned c; - unsigned i; - unsigned k; - unsigned n; - - static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - i = 0; - k = 0; - n = slen / 3 * 3; - - while (i < n) { - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - c = src[i + 2] & 0xff; - - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; - dst[k + 3] = table[c & 0x3f]; - - i += 3; - k += 4; - } - - if (n != slen) { - switch (slen - n) { - case 1: - a = src[i + 0] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[(a & 3) << 4]; - dst[k + 2] = '='; - dst[k + 3] = '='; - break; - - case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[(b & 0x0f) << 2]; - dst[k + 3] = '='; - break; - } - } - - return dlen; -} - - -static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= slen * 2 && - "not enough space provided for hex encode"); - - dlen = slen * 2; - for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { - static const char hex[] = "0123456789abcdef"; - uint8_t val = static_cast(src[i]); - dst[k + 0] = hex[val >> 4]; - dst[k + 1] = hex[val & 15]; - } - - return dlen; -} - - - -static Local Encode(const char* buf, - size_t buflen, - enum Nan::Encoding encoding) { - assert(buflen <= node::Buffer::kMaxLength); - if (!buflen && encoding != Nan::BUFFER) - return NanNew(""); - - Local val; - switch (encoding) { - case Nan::BUFFER: - return NanNewBufferHandle(buf, buflen); - - case Nan::ASCII: - if (contains_non_ascii(buf, buflen)) { - char* out = new char[buflen]; - force_ascii(buf, out, buflen); - val = NanNew(out, buflen); - delete[] out; - } else { - val = NanNew(buf, buflen); - } - break; - - case Nan::UTF8: - val = NanNew(buf, buflen); - break; - - case Nan::BINARY: { - // TODO(isaacs) use ExternalTwoByteString? - const unsigned char *cbuf = reinterpret_cast(buf); - uint16_t * twobytebuf = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i++) { - // XXX is the following line platform independent? - twobytebuf[i] = cbuf[i]; - } - val = NanNew(twobytebuf, buflen); - delete[] twobytebuf; - break; - } - - case Nan::BASE64: { - size_t dlen = base64_encoded_size(buflen); - char* dst = new char[dlen]; - - size_t written = base64_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - case Nan::UCS2: { - const uint16_t* data = reinterpret_cast(buf); - val = NanNew(data, buflen / 2); - break; - } - - case Nan::HEX: { - size_t dlen = buflen * 2; - char* dst = new char[dlen]; - size_t written = hex_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = NanNew(dst, dlen); - delete[] dst; - break; - } - - default: - assert(0 && "unknown encoding"); - break; - } - - return val; -} - -#undef base64_encoded_size - -} // namespace NanIntern - -#endif // NAN_STRING_BYTES_H_ diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100644 index 9247217..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.9", - "description": "Kerberos library for Node.js", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "dependencies": { - "nan": "1.6.2" - }, - "devDependencies": { - "nodeunit": "latest" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.9", - "_shasum": "595bf97e7e8aae5401ae313aea57bbf402e799c5", - "_from": "kerberos@0.0.9", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "595bf97e7e8aae5401ae313aea57bbf402e799c5", - "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.9.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.9.tgz" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore deleted file mode 100644 index 38344f8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md deleted file mode 100644 index 3fb3e80..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# readable-stream - -***Node-core streams for userland*** - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) - -This package is a mirror of the Streams2 and Streams3 implementations in Node-core. - -If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. - -**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. - -**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js deleted file mode 100644 index ca807af..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index b513d61..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 6307220..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = require('stream'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; - - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } - - if (state.length === 0) - endReadable(this); - - return ret; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted && state.calledRead) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index 4bdaa4f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b41..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js deleted file mode 100644 index 9074e8e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json deleted file mode 100644 index 2155d11..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.1", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/isaacs/core-util-is", - "_id": "core-util-is@1.0.1", - "dist": { - "shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" - }, - "_from": "core-util-is@>=1.0.0 <1.1.0", - "_npmVersion": "1.3.23", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js deleted file mode 100644 index 007fa10..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js deleted file mode 100644 index 29f5e24..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json deleted file mode 100644 index 005588b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@2.0.1", - "dist": { - "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" - }, - "_from": "inherits@>=2.0.1 <2.1.0", - "_npmVersion": "1.3.8", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", - "readme": "ERROR: No README data found!", - "homepage": "https://github.com/isaacs/inherits" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js deleted file mode 100644 index fc53012..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md deleted file mode 100644 index 052a62b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md +++ /dev/null @@ -1,54 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -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. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js deleted file mode 100644 index ec58596..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Require the given path. - * - * @param {String} path - * @return {Object} exports - * @api public - */ - -function require(path, parent, orig) { - var resolved = require.resolve(path); - - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; - module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); - } - - return module.exports; -} - -/** - * Registered modules. - */ - -require.modules = {}; - -/** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. - * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - var index = path + '/index.js'; - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - } - - if (require.aliases.hasOwnProperty(index)) { - return require.aliases[index]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path - * @param {Function} definition - * @api private - */ - -require.register = function(path, definition) { - require.modules[path] = definition; -}; - -/** - * Alias a module definition. - * - * @param {String} from - * @param {String} to - * @api private - */ - -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; - }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; -}; -require.register("isarray/index.js", function(exports, require, module){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -}); -require.alias("isarray/index.js", "isarray/index.js"); - diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js deleted file mode 100644 index 5f5ad45..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json deleted file mode 100644 index 19228ab..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "isarray", - "description": "Array#isArray for older browsers", - "version": "0.0.1", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "homepage": "https://github.com/juliangruber/isarray", - "main": "index.js", - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "*" - }, - "keywords": [ - "browser", - "isarray", - "array" - ], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT", - "_id": "isarray@0.0.1", - "dist": { - "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" - }, - "_from": "isarray@0.0.1", - "_npmVersion": "1.2.18", - "_npmUser": { - "name": "juliangruber", - "email": "julian@juliangruber.com" - }, - "maintainers": [ - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - } - ], - "directories": {}, - "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "bugs": { - "url": "https://github.com/juliangruber/isarray/issues" - }, - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore deleted file mode 100644 index 206320c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE deleted file mode 100644 index 6de584a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -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. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md deleted file mode 100644 index 4d2aa00..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**string_decoder.js** (`require('string_decoder')`) from Node.js core - -Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. - -Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** - -The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js deleted file mode 100644 index b00e54f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var Buffer = require('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json deleted file mode 100644 index 0364d54..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "string_decoder", - "version": "0.10.31", - "description": "The string_decoder module from Node core", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "tap": "~0.4.8" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "_id": "string_decoder@0.10.31", - "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "_from": "string_decoder@>=0.10.0 <0.11.0", - "_npmVersion": "1.4.23", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json deleted file mode 100644 index 153fb54..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "readable-stream", - "version": "1.0.33", - "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "isarray": "0.0.1", - "string_decoder": "~0.10.x", - "inherits": "~2.0.1" - }, - "devDependencies": { - "tap": "~0.2.6" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "browser": { - "util": false - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "gitHead": "0bf97a117c5646556548966409ebc57a6dda2638", - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "homepage": "https://github.com/isaacs/readable-stream", - "_id": "readable-stream@1.0.33", - "_shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", - "_from": "readable-stream@latest", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "3a360dd66c1b1d7fd4705389860eda1d0f61126c", - "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.33.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js deleted file mode 100644 index 27e8d8a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js deleted file mode 100644 index 5d482f0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js b/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js deleted file mode 100644 index e1e9efd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js deleted file mode 100644 index 75d1de1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/any.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -function Promise$_Any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} - -Promise.any = function Promise$Any(promises) { - return Promise$_Any(promises); -}; - -Promise.prototype.any = function Promise$any() { - return Promise$_Any(this); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js deleted file mode 100644 index 50004c9..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/async.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var schedule = require("./schedule.js"); -var Queue = require("./queue.js"); -var errorObj = require("./util.js").errorObj; -var tryCatch1 = require("./util.js").tryCatch1; -var _process = typeof process !== "undefined" ? process : void 0; - -function Async() { - this._isTickUsed = false; - this._schedule = schedule; - this._length = 0; - this._lateBuffer = new Queue(16); - this._functionBuffer = new Queue(65536); - var self = this; - this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() { - self._consumeFunctionBuffer(); - }; -} - -Async.prototype.haveItemsQueued = function Async$haveItemsQueued() { - return this._length > 0; -}; - -Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) { - if (_process !== void 0 && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - this._lateBuffer.push(fn, receiver, arg); - this._queueTick(); -}; - -Async.prototype.invoke = function Async$invoke(fn, receiver, arg) { - if (_process !== void 0 && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - var functionBuffer = this._functionBuffer; - functionBuffer.push(fn, receiver, arg); - this._length = functionBuffer.length(); - this._queueTick(); -}; - -Async.prototype._consumeFunctionBuffer = -function Async$_consumeFunctionBuffer() { - var functionBuffer = this._functionBuffer; - while (functionBuffer.length() > 0) { - var fn = functionBuffer.shift(); - var receiver = functionBuffer.shift(); - var arg = functionBuffer.shift(); - fn.call(receiver, arg); - } - this._reset(); - this._consumeLateBuffer(); -}; - -Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() { - var buffer = this._lateBuffer; - while(buffer.length() > 0) { - var fn = buffer.shift(); - var receiver = buffer.shift(); - var arg = buffer.shift(); - var res = tryCatch1(fn, receiver, arg); - if (res === errorObj) { - this._queueTick(); - if (fn.domain != null) { - fn.domain.emit("error", res.e); - } else { - throw res.e; - } - } - } -}; - -Async.prototype._queueTick = function Async$_queue() { - if (!this._isTickUsed) { - this._schedule(this.consumeFunctionBuffer); - this._isTickUsed = true; - } -}; - -Async.prototype._reset = function Async$_reset() { - this._isTickUsed = false; - this._length = 0; -}; - -module.exports = new Async(); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js deleted file mode 100644 index 6fd85f1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/bluebird.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var Promise = require("./promise.js")(); -module.exports = Promise; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js deleted file mode 100644 index dfaaf5c..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/call_get.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -function makeMethodCaller (methodName) { - return new Function("obj", " \n\ - 'use strict' \n\ - var len = this.length; \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: return obj.methodName.apply(obj, this); \n\ - } \n\ - ".replace(/methodName/g, methodName)); -} - -function makeGetter (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -} - -function getCompiled(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -} - -function getMethodCaller(name) { - return getCompiled(name, makeMethodCaller, callerCache); -} - -function getGetter(name) { - return getCompiled(name, makeGetter, getterCache); -} - -function caller(obj) { - return obj[this.pop()].apply(obj, this); -} -Promise.prototype.call = function Promise$call(methodName) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then(maybeCaller, void 0, void 0, args, void 0); - } - } - args.push(methodName); - return this._then(caller, void 0, void 0, args, void 0); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - return obj[this]; -} -Promise.prototype.get = function Promise$get(propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, void 0, void 0, propertyName, void 0); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js deleted file mode 100644 index d3022b6..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/cancel.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var errors = require("./errors.js"); -var canAttach = errors.canAttach; -var async = require("./async.js"); -var CancellationError = errors.CancellationError; - -Promise.prototype._cancel = function Promise$_cancel(reason) { - if (!this.isCancellable()) return this; - var parent; - var promiseToReject = this; - while ((parent = promiseToReject._cancellationParent) !== void 0 && - parent.isCancellable()) { - promiseToReject = parent; - } - promiseToReject._attachExtraTrace(reason); - promiseToReject._rejectUnchecked(reason); -}; - -Promise.prototype.cancel = function Promise$cancel(reason) { - if (!this.isCancellable()) return this; - reason = reason !== void 0 - ? (canAttach(reason) ? reason : new Error(reason + "")) - : new CancellationError(); - async.invokeLater(this._cancel, this, reason); - return this; -}; - -Promise.prototype.cancellable = function Promise$cancellable() { - if (this._cancellable()) return this; - this._setCancellable(); - this._cancellationParent = void 0; - return this; -}; - -Promise.prototype.uncancellable = function Promise$uncancellable() { - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 2 | 4); - ret._follow(this); - ret._unsetCancellable(); - return ret; -}; - -Promise.prototype.fork = -function Promise$fork(didFulfill, didReject, didProgress) { - var ret = this._then(didFulfill, didReject, didProgress, - void 0, void 0); - - ret._setCancellable(); - ret._cancellationParent = void 0; - return ret; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js deleted file mode 100644 index 89fa8ca..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/captured_trace.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function() { -var inherits = require("./util.js").inherits; -var defineProperty = require("./es5.js").defineProperty; - -var rignore = new RegExp( - "\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" + - "tryCatch(?:1|2|3|4|Apply)|new \\w*PromiseArray|" + - "\\w*PromiseArray\\.\\w*PromiseArray|" + - "setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" + - "process._tickCallback|nextTick|Async\\$\\w+)\\b" -); - -var rtraceline = null; -var formatStack = null; - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj.toString(); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function CapturedTrace(ignoreUntil, isTopLevel) { - this.captureStackTrace(CapturedTrace, isTopLevel); - -} -inherits(CapturedTrace, Error); - -CapturedTrace.prototype.captureStackTrace = -function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) { - captureStackTrace(this, ignoreUntil, isTopLevel); -}; - -CapturedTrace.possiblyUnhandledRejection = -function CapturedTrace$PossiblyUnhandledRejection(reason) { - if (typeof console === "object") { - var message; - if (typeof reason === "object" || typeof reason === "function") { - var stack = reason.stack; - message = "Possibly unhandled " + formatStack(stack, reason); - } else { - message = "Possibly unhandled " + String(reason); - } - if (typeof console.error === "function" || - typeof console.error === "object") { - console.error(message); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -}; - -CapturedTrace.combine = function CapturedTrace$Combine(current, prev) { - var curLast = current.length - 1; - for (var i = prev.length - 1; i >= 0; --i) { - var line = prev[i]; - if (current[curLast] === line) { - current.pop(); - curLast--; - } else { - break; - } - } - - current.push("From previous event:"); - var lines = current.concat(prev); - - var ret = []; - - for (var i = 0, len = lines.length; i < len; ++i) { - - if (((rignore.test(lines[i]) && rtraceline.test(lines[i])) || - (i > 0 && !rtraceline.test(lines[i])) && - lines[i] !== "From previous event:") - ) { - continue; - } - ret.push(lines[i]); - } - return ret; -}; - -CapturedTrace.protectErrorMessageNewlines = function(stack) { - for (var i = 0; i < stack.length; ++i) { - if (rtraceline.test(stack[i])) { - break; - } - } - - if (i <= 1) return; - - var errorMessageLines = []; - for (var j = 0; j < i; ++j) { - errorMessageLines.push(stack.shift()); - } - stack.unshift(errorMessageLines.join("\u0002\u0000\u0001")); -}; - -CapturedTrace.isSupported = function CapturedTrace$IsSupported() { - return typeof captureStackTrace === "function"; -}; - -var captureStackTrace = (function stackDetection() { - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - rtraceline = /^\s*at\s*/; - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - - - }; - var captureStackTrace = Error.captureStackTrace; - return function CapturedTrace$_captureStackTrace( - receiver, ignoreUntil) { - captureStackTrace(receiver, ignoreUntil); - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - typeof "".startsWith === "function" && - (err.stack.startsWith("stackDetection@")) && - stackDetection.name === "stackDetection") { - - defineProperty(Error, "stackTraceLimit", { - writable: true, - enumerable: false, - configurable: false, - value: 25 - }); - rtraceline = /@/; - var rline = /[@\n]/; - - formatStack = function(stack, error) { - if (typeof stack === "string") { - return (error.name + ". " + error.message + "\n" + stack); - } - - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return function captureStackTrace(o) { - var stack = new Error().stack; - var split = stack.split(rline); - var len = split.length; - var ret = ""; - for (var i = 0; i < len; i += 2) { - ret += split[i]; - ret += "@"; - ret += split[i + 1]; - ret += "\n"; - } - o.stack = ret; - }; - } else { - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return null; - } -})(); - -return CapturedTrace; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js deleted file mode 100644 index 25d9f73..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/catch_filter.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; -var keys = require("./es5.js").keys; -var TypeError = errors.TypeError; - -function CatchFilter(instances, callback, promise) { - this._instances = instances; - this._callback = callback; - this._promise = promise; -} - -function CatchFilter$_safePredicate(predicate, e) { - var safeObject = {}; - var retfilter = tryCatch1(predicate, safeObject, e); - - if (retfilter === errorObj) return retfilter; - - var safeKeys = keys(safeObject); - if (safeKeys.length) { - errorObj.e = new TypeError( - "Catch filter must inherit from Error " - + "or be a simple predicate function"); - return errorObj; - } - return retfilter; -} - -CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) { - var cb = this._callback; - var promise = this._promise; - var boundTo = promise._boundTo; - for (var i = 0, len = this._instances.length; i < len; ++i) { - var item = this._instances[i]; - var itemIsErrorType = item === Error || - (item != null && item.prototype instanceof Error); - - if (itemIsErrorType && e instanceof item) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } else if (typeof item === "function" && !itemIsErrorType) { - var shouldHandle = CatchFilter$_safePredicate(item, e); - if (shouldHandle === errorObj) { - var trace = errors.canAttach(errorObj.e) - ? errorObj.e - : new Error(errorObj.e + ""); - this._promise._attachExtraTrace(trace); - e = errorObj.e; - break; - } else if (shouldHandle) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } - } - } - NEXT_FILTER.e = e; - return NEXT_FILTER; -}; - -return CatchFilter; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js deleted file mode 100644 index 3386a19..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/direct_resolve.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var util = require("./util.js"); -var isPrimitive = util.isPrimitive; -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; - -module.exports = function(Promise) { -var returner = function Promise$_returner() { - return this; -}; -var thrower = function Promise$_thrower() { - throw this; -}; - -var wrapper = function Promise$_wrapper(value, action) { - if (action === 1) { - return function Promise$_thrower() { - throw value; - }; - } else if (action === 2) { - return function Promise$_returner() { - return value; - }; - } -}; - - -Promise.prototype["return"] = -Promise.prototype.thenReturn = -function Promise$thenReturn(value) { - if (wrapsPrimitiveReceiver && isPrimitive(value)) { - return this._then( - wrapper(value, 2), - void 0, - void 0, - void 0, - void 0 - ); - } - return this._then(returner, void 0, void 0, value, void 0); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = -function Promise$thenThrow(reason) { - if (wrapsPrimitiveReceiver && isPrimitive(reason)) { - return this._then( - wrapper(reason, 1), - void 0, - void 0, - void 0, - void 0 - ); - } - return this._then(thrower, void 0, void 0, reason, void 0); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js deleted file mode 100644 index c89a144..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/each.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; - -Promise.prototype.each = function Promise$each(fn) { - return PromiseReduce(this, fn, null, INTERNAL); -}; - -Promise.each = function Promise$Each(promises, fn) { - return PromiseReduce(promises, fn, null, INTERNAL); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors_api_rejection.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors_api_rejection.js deleted file mode 100644 index e953e3b..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/errors_api_rejection.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var TypeError = require('./errors.js').TypeError; - -function apiRejection(msg) { - var error = new TypeError(msg); - var ret = Promise.rejected(error); - var parent = ret._peekContext(); - if (parent != null) { - parent._attachExtraTrace(error); - } - return ret; -} - -return apiRejection; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js deleted file mode 100644 index d8f05b3..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/es5.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -var isES5 = (function(){ - "use strict"; - return this === void 0; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - keys: Object.keys, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5 - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function ObjectKeys(o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - } - - var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) { - o[key] = desc.value; - return o; - } - - var ObjectFreeze = function ObjectFreeze(obj) { - return obj; - } - - var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - } - - var ArrayIsArray = function ArrayIsArray(obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - } - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - defineProperty: ObjectDefineProperty, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5 - }; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js deleted file mode 100644 index 08f67eb..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/filter.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function Promise$filter(fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function Promise$Filter(promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js deleted file mode 100644 index 0f68296..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/finally.js +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, NEXT_FILTER, cast) { -var util = require("./util.js"); -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; -var isPrimitive = util.isPrimitive; -var thrower = util.thrower; - -function returnThis() { - return this; -} -function throwThis() { - throw this; -} -function return$(r) { - return function Promise$_returner() { - return r; - }; -} -function throw$(r) { - return function Promise$_thrower() { - throw r; - }; -} -function promisedFinally(ret, reasonOrValue, isFulfilled) { - var then; - if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { - then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); - } else { - then = isFulfilled ? returnThis : throwThis; - } - return ret._then(then, thrower, void 0, reasonOrValue, void 0); -} - -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo) - : handler(); - - if (ret !== void 0) { - var maybePromise = cast(ret, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, reasonOrValue, - promise.isFulfilled()); - } - } - - if (promise.isRejected()) { - NEXT_FILTER.e = reasonOrValue; - return NEXT_FILTER; - } else { - return reasonOrValue; - } -} - -function tapHandler(value) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo, value) - : handler(value); - - if (ret !== void 0) { - var maybePromise = cast(ret, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, value, true); - } - } - return value; -} - -Promise.prototype._passThroughHandler = -function Promise$_passThroughHandler(handler, isFinally) { - if (typeof handler !== "function") return this.then(); - - var promiseAndHandler = { - promise: this, - handler: handler - }; - - return this._then( - isFinally ? finallyHandler : tapHandler, - isFinally ? finallyHandler : void 0, void 0, - promiseAndHandler, void 0); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function Promise$finally(handler) { - return this._passThroughHandler(handler, true); -}; - -Promise.prototype.tap = function Promise$tap(handler) { - return this._passThroughHandler(handler, false); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js deleted file mode 100644 index 58d418f..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/generators.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, apiRejection, INTERNAL, cast) { -var errors = require("./errors.js"); -var TypeError = errors.TypeError; -var deprecated = require("./util.js").deprecated; -var util = require("./util.js"); -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers) { - var _errorObj = errorObj; - var _Promise = Promise; - var len = yieldHandlers.length; - for (var i = 0; i < len; ++i) { - var result = tryCatch1(yieldHandlers[i], void 0, value); - if (result === _errorObj) { - return _Promise.reject(_errorObj.e); - } - var maybePromise = cast(result, promiseFromYieldHandler); - if (maybePromise instanceof _Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler) { - var promise = this._promise = new Promise(INTERNAL); - promise._setTrace(void 0); - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = void 0; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; -} - -PromiseSpawn.prototype.promise = function PromiseSpawn$promise() { - return this._promise; -}; - -PromiseSpawn.prototype._run = function PromiseSpawn$_run() { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = void 0; - this._next(void 0); -}; - -PromiseSpawn.prototype._continue = function PromiseSpawn$_continue(result) { - if (result === errorObj) { - this._generator = void 0; - var trace = errors.canAttach(result.e) - ? result.e : new Error(result.e + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(result.e, trace); - return; - } - - var value = result.value; - if (result.done === true) { - this._generator = void 0; - if (!this._promise._tryFollow(value)) { - this._promise._fulfill(value); - } - } else { - var maybePromise = cast(value, void 0); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, this._yieldHandlers); - if (maybePromise === null) { - this._throw(new TypeError("A value was yielded that could not be treated as a promise")); - return; - } - } - maybePromise._then( - this._next, - this._throw, - void 0, - this, - null - ); - } -}; - -PromiseSpawn.prototype._throw = function PromiseSpawn$_throw(reason) { - if (errors.canAttach(reason)) - this._promise._attachExtraTrace(reason); - this._continue( - tryCatch1(this._generator["throw"], this._generator, reason) - ); -}; - -PromiseSpawn.prototype._next = function PromiseSpawn$_next(value) { - this._continue( - tryCatch1(this._generator.next, this._generator, value) - ); -}; - -Promise.coroutine = -function Promise$Coroutine(generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(void 0, void 0, yieldHandler); - spawn._generator = generator; - spawn._next(void 0); - return spawn.promise(); - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function"); - yieldHandlers.push(fn); -}; - -Promise.spawn = function Promise$Spawn(generatorFunction) { - deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead."); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js deleted file mode 100644 index 123e66b..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/join.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, cast, INTERNAL) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - - -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var caller = function(count) { - var values = []; - for (var i = 1; i <= count; ++i) values.push("holder.p" + i); - return new Function("holder", " \n\ - 'use strict'; \n\ - var callback = holder.fn; \n\ - return callback(values); \n\ - ".replace(/values/g, values.join(", "))); - }; - var thenCallbacks = []; - var callers = [void 0]; - for (var i = 1; i <= 5; ++i) { - thenCallbacks.push(thenCallback(i)); - callers.push(caller(i)); - } - - var Holder = function(total, fn) { - this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; - this.fn = fn; - this.total = total; - this.now = 0; - }; - - Holder.prototype.callers = callers; - Holder.prototype.checkFulfillment = function(promise) { - var now = this.now; - now++; - var total = this.total; - if (now >= total) { - var handler = this.callers[total]; - var ret = tryCatch1(handler, void 0, this); - if (ret === errorObj) { - promise._rejectUnchecked(ret.e); - } else if (!promise._tryFollow(ret)) { - promise._fulfillUnchecked(ret); - } - } else { - this.now = now; - } - }; -} - - - - -Promise.join = function Promise$Join() { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (last < 6 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - var holder = new Holder(last, fn); - var reject = ret._reject; - var callbacks = thenCallbacks; - for (var i = 0; i < last; ++i) { - var maybePromise = cast(arguments[i], void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._then(callbacks[i], reject, - void 0, ret, holder); - } else if (maybePromise.isFulfilled()) { - callbacks[i].call(ret, - maybePromise._settledValue, holder); - } else { - ret._reject(maybePromise._settledValue); - maybePromise._unsetRejectionIsUnhandled(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - return ret; - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - var ret = new PromiseArray(args).promise(); - return fn !== void 0 ? ret.spread(fn) : ret; -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js deleted file mode 100644 index ecc9247..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/map.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, cast, INTERNAL) { -var util = require("./util.js"); -var tryCatch3 = util.tryCatch3; -var errorObj = util.errorObj; -var PENDING = {}; -var EMPTY_ARRAY = []; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._callback = fn; - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = limit >= 1 ? [] : EMPTY_ARRAY; - this._init$(void 0, -2); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._init = function MappingPromiseArray$_init() {}; - -MappingPromiseArray.prototype._promiseFulfilled = -function MappingPromiseArray$_promiseFulfilled(value, index) { - var values = this._values; - if (values === null) return; - - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - if (values[index] === PENDING) { - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return; - } - if (preservedValues !== null) preservedValues[index] = value; - - var callback = this._callback; - var receiver = this._promise._boundTo; - var ret = tryCatch3(callback, receiver, value, index, length); - if (ret === errorObj) return this._reject(ret.e); - - var maybePromise = cast(ret, void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - if (limit >= 1) this._inFlight++; - values[index] = PENDING; - return maybePromise._proxyPromiseArray(this, index); - } else if (maybePromise.isFulfilled()) { - ret = maybePromise.value(); - } else { - maybePromise._unsetRejectionIsUnhandled(); - return this._reject(maybePromise.reason()); - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - - } -}; - -MappingPromiseArray.prototype._drainQueue = -function MappingPromiseArray$_drainQueue() { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = -function MappingPromiseArray$_filter(booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = -function MappingPromiseArray$preserveValues() { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - var limit = typeof options === "object" && options !== null - ? options.concurrency - : 0; - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter); -} - -Promise.prototype.map = function Promise$map(fn, options) { - if (typeof fn !== "function") return apiRejection("fn must be a function"); - - return map(this, fn, options, null).promise(); -}; - -Promise.map = function Promise$Map(promises, fn, options, _filter) { - if (typeof fn !== "function") return apiRejection("fn must be a function"); - return map(promises, fn, options, _filter).promise(); -}; - - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js deleted file mode 100644 index e5658d6..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/nodeify.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var util = require("./util.js"); -var async = require("./async.js"); -var tryCatch2 = util.tryCatch2; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -function thrower(r) { - throw r; -} - -function Promise$_spreadAdapter(val, receiver) { - if (!util.isArray(val)) return Promise$_successAdapter(val, receiver); - var ret = util.tryCatchApply(this, [null].concat(val), receiver); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} - -function Promise$_successAdapter(val, receiver) { - var nodeback = this; - var ret = val === void 0 - ? tryCatch1(nodeback, receiver, null) - : tryCatch2(nodeback, receiver, null, val); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} -function Promise$_errorAdapter(reason, receiver) { - var nodeback = this; - var ret = tryCatch1(nodeback, receiver, reason); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} - -Promise.prototype.nodeify = function Promise$nodeify(nodeback, options) { - if (typeof nodeback == "function") { - var adapter = Promise$_successAdapter; - if (options !== void 0 && Object(options).spread) { - adapter = Promise$_spreadAdapter; - } - this._then( - adapter, - Promise$_errorAdapter, - void 0, - nodeback, - this._boundTo - ); - } - return this; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js deleted file mode 100644 index 640f882..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/progress.js +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -Promise.prototype.progressed = function Promise$progressed(handler) { - return this._then(void 0, void 0, handler, void 0, void 0); -}; - -Promise.prototype._progress = function Promise$_progress(progressValue) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._progressUnchecked(progressValue); - -}; - -Promise.prototype._clearFirstHandlerData$Base = -Promise.prototype._clearFirstHandlerData; -Promise.prototype._clearFirstHandlerData = -function Promise$_clearFirstHandlerData() { - this._clearFirstHandlerData$Base(); - this._progressHandler0 = void 0; -}; - -Promise.prototype._progressHandlerAt = -function Promise$_progressHandlerAt(index) { - return index === 0 - ? this._progressHandler0 - : this[(index << 2) + index - 5 + 2]; -}; - -Promise.prototype._doProgressWith = -function Promise$_doProgressWith(progression) { - var progressValue = progression.value; - var handler = progression.handler; - var promise = progression.promise; - var receiver = progression.receiver; - - var ret = tryCatch1(handler, receiver, progressValue); - if (ret === errorObj) { - if (ret.e != null && - ret.e.name !== "StopProgressPropagation") { - var trace = errors.canAttach(ret.e) - ? ret.e : new Error(ret.e + ""); - promise._attachExtraTrace(trace); - promise._progress(ret.e); - } - } else if (ret instanceof Promise) { - ret._then(promise._progress, null, null, promise, void 0); - } else { - promise._progress(ret); - } -}; - - -Promise.prototype._progressUnchecked = -function Promise$_progressUnchecked(progressValue) { - if (!this.isPending()) return; - var len = this._length(); - var progress = this._progress; - for (var i = 0; i < len; i++) { - var handler = this._progressHandlerAt(i); - var promise = this._promiseAt(i); - if (!(promise instanceof Promise)) { - var receiver = this._receiverAt(i); - if (typeof handler === "function") { - handler.call(receiver, progressValue, promise); - } else if (receiver instanceof Promise && receiver._isProxied()) { - receiver._progressUnchecked(progressValue); - } else if (receiver instanceof PromiseArray) { - receiver._promiseProgressed(progressValue, promise); - } - continue; - } - - if (typeof handler === "function") { - async.invoke(this._doProgressWith, this, { - handler: handler, - promise: promise, - receiver: this._receiverAt(i), - value: progressValue - }); - } else { - async.invoke(progress, promise, progressValue); - } - } -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js deleted file mode 100644 index 08c0ff6..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise.js +++ /dev/null @@ -1,1077 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict(bluebird) { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -module.exports = function() { -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); - -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {e: null}; - -var cast = require("./thenables.js")(Promise, INTERNAL); -var PromiseArray = require("./promise_array.js")(Promise, INTERNAL, cast); -var CapturedTrace = require("./captured_trace.js")(); -var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); -var PromiseResolver = require("./promise_resolver.js"); - -var isArray = util.isArray; - -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var tryCatch2 = util.tryCatch2; -var tryCatchApply = util.tryCatchApply; -var RangeError = errors.RangeError; -var TypeError = errors.TypeError; -var CancellationError = errors.CancellationError; -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var originatesFromRejection = errors.originatesFromRejection; -var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection; -var canAttach = errors.canAttach; -var thrower = util.thrower; -var apiRejection = require("./errors_api_rejection")(Promise); - - -var makeSelfResolutionError = function Promise$_makeSelfResolutionError() { - return new TypeError("circular promise resolution chain"); -}; - -function Promise(resolver) { - if (typeof resolver !== "function") { - throw new TypeError("the promise constructor requires a resolver function"); - } - if (this.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly"); - } - this._bitField = 0; - this._fulfillmentHandler0 = void 0; - this._rejectionHandler0 = void 0; - this._promise0 = void 0; - this._receiver0 = void 0; - this._settledValue = void 0; - this._boundTo = void 0; - if (resolver !== INTERNAL) this._resolveFromResolver(resolver); -} - -function returnFirstElement(elements) { - return elements[0]; -} - -Promise.prototype.bind = function Promise$bind(thisArg) { - var maybePromise = cast(thisArg, void 0); - var ret = new Promise(INTERNAL); - if (maybePromise instanceof Promise) { - var binder = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - var p = Promise.all([this, binder]).then(returnFirstElement); - ret._follow(p); - } else { - ret._follow(this); - ret._setBoundTo(thisArg); - } - ret._propagateFrom(this, 2 | 1); - return ret; -}; - -Promise.prototype.toString = function Promise$toString() { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = -function Promise$catch(fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (typeof item === "function") { - catchInstances[j++] = item; - } else { - var catchFilterTypeError = - new TypeError( - "A catch filter must be an error constructor " - + "or a filter function"); - - this._attachExtraTrace(catchFilterTypeError); - async.invoke(this._reject, this, catchFilterTypeError); - return; - } - } - catchInstances.length = j; - fn = arguments[i]; - - this._resetTrace(); - var catchFilter = new CatchFilter(catchInstances, fn, this); - return this._then(void 0, catchFilter.doFilter, void 0, - catchFilter, void 0); - } - return this._then(void 0, fn, void 0, void 0, void 0); -}; - -Promise.prototype.then = -function Promise$then(didFulfill, didReject, didProgress) { - return this._then(didFulfill, didReject, didProgress, - void 0, void 0); -}; - - -Promise.prototype.done = -function Promise$done(didFulfill, didReject, didProgress) { - var promise = this._then(didFulfill, didReject, didProgress, - void 0, void 0); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function Promise$spread(didFulfill, didReject) { - return this._then(didFulfill, didReject, void 0, - APPLY, void 0); -}; - -Promise.prototype.isCancellable = function Promise$isCancellable() { - return !this.isResolved() && - this._cancellable(); -}; - -Promise.prototype.toJSON = function Promise$toJSON() { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: void 0, - rejectionReason: void 0 - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this._settledValue; - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this._settledValue; - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function Promise$all() { - return new PromiseArray(this).promise(); -}; - - -Promise.is = function Promise$Is(val) { - return val instanceof Promise; -}; - -Promise.all = function Promise$All(promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.prototype.error = function Promise$_error(fn) { - return this.caught(originatesFromRejection, fn); -}; - -Promise.prototype._resolveFromSyncValue = -function Promise$_resolveFromSyncValue(value) { - if (value === errorObj) { - this._cleanValues(); - this._setRejected(); - this._settledValue = value.e; - this._ensurePossibleRejectionHandled(); - } else { - var maybePromise = cast(value, void 0); - if (maybePromise instanceof Promise) { - this._follow(maybePromise); - } else { - this._cleanValues(); - this._setFulfilled(); - this._settledValue = value; - } - } -}; - -Promise.method = function Promise$_Method(fn) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); - } - return function Promise$_method() { - var value; - switch(arguments.length) { - case 0: value = tryCatch1(fn, this, void 0); break; - case 1: value = tryCatch1(fn, this, arguments[0]); break; - case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break; - default: - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - value = tryCatchApply(fn, args, this); break; - } - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) { - if (typeof fn !== "function") { - return apiRejection("fn must be a function"); - } - var value = isArray(args) - ? tryCatchApply(fn, args, ctx) - : tryCatch1(fn, ctx, args); - - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.defer = Promise.pending = function Promise$Defer() { - var promise = new Promise(INTERNAL); - promise._setTrace(void 0); - return new PromiseResolver(promise); -}; - -Promise.bind = function Promise$Bind(thisArg) { - var maybePromise = cast(thisArg, void 0); - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - - if (maybePromise instanceof Promise) { - var p = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - ret._follow(p); - } else { - ret._setBoundTo(thisArg); - ret._setFulfilled(); - } - return ret; -}; - -Promise.cast = function Promise$_Cast(obj) { - var ret = cast(obj, void 0); - if (!(ret instanceof Promise)) { - var val = ret; - ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._setFulfilled(); - ret._cleanValues(); - ret._settledValue = val; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function Promise$Reject(reason) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - markAsOriginatingFromRejection(reason); - ret._cleanValues(); - ret._setRejected(); - ret._settledValue = reason; - if (!canAttach(reason)) { - var trace = new Error(reason + ""); - ret._setCarriedStackTrace(trace); - } - ret._ensurePossibleRejectionHandled(); - return ret; -}; - -Promise.onPossiblyUnhandledRejection = -function Promise$OnPossiblyUnhandledRejection(fn) { - CapturedTrace.possiblyUnhandledRejection = typeof fn === "function" - ? fn : void 0; -}; - -var unhandledRejectionHandled; -Promise.onUnhandledRejectionHandled = -function Promise$onUnhandledRejectionHandled(fn) { - unhandledRejectionHandled = typeof fn === "function" ? fn : void 0; -}; - -var debugging = false || !!( - typeof process !== "undefined" && - typeof process.execPath === "string" && - typeof process.env === "object" && - (process.env["BLUEBIRD_DEBUG"] || - process.env["NODE_ENV"] === "development") -); - - -Promise.longStackTraces = function Promise$LongStackTraces() { - if (async.haveItemsQueued() && - debugging === false - ) { - throw new Error("cannot enable long stack traces after promises have been created"); - } - debugging = CapturedTrace.isSupported(); -}; - -Promise.hasLongStackTraces = function Promise$HasLongStackTraces() { - return debugging && CapturedTrace.isSupported(); -}; - -Promise.prototype._then = -function Promise$_then( - didFulfill, - didReject, - didProgress, - receiver, - internalData -) { - var haveInternalData = internalData !== void 0; - var ret = haveInternalData ? internalData : new Promise(INTERNAL); - - if (!haveInternalData) { - if (debugging) { - var haveSameContext = this._peekContext() === this._traceParent; - ret._traceParent = haveSameContext ? this._traceParent : this; - } - ret._propagateFrom(this, 7); - } - - var callbackIndex = - this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - - if (this.isResolved()) { - async.invoke(this._queueSettleAt, this, callbackIndex); - } - - return ret; -}; - -Promise.prototype._length = function Promise$_length() { - return this._bitField & 262143; -}; - -Promise.prototype._isFollowingOrFulfilledOrRejected = -function Promise$_isFollowingOrFulfilledOrRejected() { - return (this._bitField & 939524096) > 0; -}; - -Promise.prototype._isFollowing = function Promise$_isFollowing() { - return (this._bitField & 536870912) === 536870912; -}; - -Promise.prototype._setLength = function Promise$_setLength(len) { - this._bitField = (this._bitField & -262144) | - (len & 262143); -}; - -Promise.prototype._setFulfilled = function Promise$_setFulfilled() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._setRejected = function Promise$_setRejected() { - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._setFollowing = function Promise$_setFollowing() { - this._bitField = this._bitField | 536870912; -}; - -Promise.prototype._setIsFinal = function Promise$_setIsFinal() { - this._bitField = this._bitField | 33554432; -}; - -Promise.prototype._isFinal = function Promise$_isFinal() { - return (this._bitField & 33554432) > 0; -}; - -Promise.prototype._cancellable = function Promise$_cancellable() { - return (this._bitField & 67108864) > 0; -}; - -Promise.prototype._setCancellable = function Promise$_setCancellable() { - this._bitField = this._bitField | 67108864; -}; - -Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() { - this._bitField = this._bitField & (~67108864); -}; - -Promise.prototype._setRejectionIsUnhandled = -function Promise$_setRejectionIsUnhandled() { - this._bitField = this._bitField | 2097152; -}; - -Promise.prototype._unsetRejectionIsUnhandled = -function Promise$_unsetRejectionIsUnhandled() { - this._bitField = this._bitField & (~2097152); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = -function Promise$_isRejectionUnhandled() { - return (this._bitField & 2097152) > 0; -}; - -Promise.prototype._setUnhandledRejectionIsNotified = -function Promise$_setUnhandledRejectionIsNotified() { - this._bitField = this._bitField | 524288; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = -function Promise$_unsetUnhandledRejectionIsNotified() { - this._bitField = this._bitField & (~524288); -}; - -Promise.prototype._isUnhandledRejectionNotified = -function Promise$_isUnhandledRejectionNotified() { - return (this._bitField & 524288) > 0; -}; - -Promise.prototype._setCarriedStackTrace = -function Promise$_setCarriedStackTrace(capturedTrace) { - this._bitField = this._bitField | 1048576; - this._fulfillmentHandler0 = capturedTrace; -}; - -Promise.prototype._unsetCarriedStackTrace = -function Promise$_unsetCarriedStackTrace() { - this._bitField = this._bitField & (~1048576); - this._fulfillmentHandler0 = void 0; -}; - -Promise.prototype._isCarryingStackTrace = -function Promise$_isCarryingStackTrace() { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._getCarriedStackTrace = -function Promise$_getCarriedStackTrace() { - return this._isCarryingStackTrace() - ? this._fulfillmentHandler0 - : void 0; -}; - -Promise.prototype._receiverAt = function Promise$_receiverAt(index) { - var ret = index === 0 - ? this._receiver0 - : this[(index << 2) + index - 5 + 4]; - if (this._isBound() && ret === void 0) { - return this._boundTo; - } - return ret; -}; - -Promise.prototype._promiseAt = function Promise$_promiseAt(index) { - return index === 0 - ? this._promise0 - : this[(index << 2) + index - 5 + 3]; -}; - -Promise.prototype._fulfillmentHandlerAt = -function Promise$_fulfillmentHandlerAt(index) { - return index === 0 - ? this._fulfillmentHandler0 - : this[(index << 2) + index - 5 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = -function Promise$_rejectionHandlerAt(index) { - return index === 0 - ? this._rejectionHandler0 - : this[(index << 2) + index - 5 + 1]; -}; - -Promise.prototype._addCallbacks = function Promise$_addCallbacks( - fulfill, - reject, - progress, - promise, - receiver -) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - if (receiver !== void 0) this._receiver0 = receiver; - if (typeof fulfill === "function" && !this._isCarryingStackTrace()) - this._fulfillmentHandler0 = fulfill; - if (typeof reject === "function") this._rejectionHandler0 = reject; - if (typeof progress === "function") this._progressHandler0 = progress; - } else { - var base = (index << 2) + index - 5; - this[base + 3] = promise; - this[base + 4] = receiver; - this[base + 0] = typeof fulfill === "function" - ? fulfill : void 0; - this[base + 1] = typeof reject === "function" - ? reject : void 0; - this[base + 2] = typeof progress === "function" - ? progress : void 0; - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._setProxyHandlers = -function Promise$_setProxyHandlers(receiver, promiseSlotValue) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - if (index === 0) { - this._promise0 = promiseSlotValue; - this._receiver0 = receiver; - } else { - var base = (index << 2) + index - 5; - this[base + 3] = promiseSlotValue; - this[base + 4] = receiver; - this[base + 0] = - this[base + 1] = - this[base + 2] = void 0; - } - this._setLength(index + 1); -}; - -Promise.prototype._proxyPromiseArray = -function Promise$_proxyPromiseArray(promiseArray, index) { - this._setProxyHandlers(promiseArray, index); -}; - -Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) { - promise._setProxied(); - this._setProxyHandlers(promise, -15); -}; - -Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) { - if (obj !== void 0) { - this._bitField = this._bitField | 8388608; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~8388608); - } -}; - -Promise.prototype._isBound = function Promise$_isBound() { - return (this._bitField & 8388608) === 8388608; -}; - -Promise.prototype._resolveFromResolver = -function Promise$_resolveFromResolver(resolver) { - var promise = this; - this._setTrace(void 0); - this._pushContext(); - - function Promise$_resolver(val) { - if (promise._tryFollow(val)) { - return; - } - promise._fulfill(val); - } - function Promise$_rejecter(val) { - var trace = canAttach(val) ? val : new Error(val + ""); - promise._attachExtraTrace(trace); - markAsOriginatingFromRejection(val); - promise._reject(val, trace === val ? void 0 : trace); - } - var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter); - this._popContext(); - - if (r !== void 0 && r === errorObj) { - var e = r.e; - var trace = canAttach(e) ? e : new Error(e + ""); - promise._reject(e, trace); - } -}; - -Promise.prototype._spreadSlowCase = -function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) { - var promiseForAll = new PromiseArray(values).promise(); - var promise2 = promiseForAll._then(function() { - return targetFn.apply(boundTo, arguments); - }, void 0, void 0, APPLY, void 0); - promise._follow(promise2); -}; - -Promise.prototype._callSpread = -function Promise$_callSpread(handler, promise, value) { - var boundTo = this._boundTo; - if (isArray(value)) { - for (var i = 0, len = value.length; i < len; ++i) { - if (cast(value[i], void 0) instanceof Promise) { - this._spreadSlowCase(handler, promise, value, boundTo); - return; - } - } - } - promise._pushContext(); - return tryCatchApply(handler, value, boundTo); -}; - -Promise.prototype._callHandler = -function Promise$_callHandler( - handler, receiver, promise, value) { - var x; - if (receiver === APPLY && !this.isRejected()) { - x = this._callSpread(handler, promise, value); - } else { - promise._pushContext(); - x = tryCatch1(handler, receiver, value); - } - promise._popContext(); - return x; -}; - -Promise.prototype._settlePromiseFromHandler = -function Promise$_settlePromiseFromHandler( - handler, receiver, value, promise -) { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - return; - } - var x = this._callHandler(handler, receiver, promise, value); - if (promise._isFollowing()) return; - - if (x === errorObj || x === promise || x === NEXT_FILTER) { - var err = x === promise - ? makeSelfResolutionError() - : x.e; - var trace = canAttach(err) ? err : new Error(err + ""); - if (x !== NEXT_FILTER) promise._attachExtraTrace(trace); - promise._rejectUnchecked(err, trace); - } else { - var castValue = cast(x, promise); - if (castValue instanceof Promise) { - if (castValue.isRejected() && - !castValue._isCarryingStackTrace() && - !canAttach(castValue._settledValue)) { - var trace = new Error(castValue._settledValue + ""); - promise._attachExtraTrace(trace); - castValue._setCarriedStackTrace(trace); - } - promise._follow(castValue); - promise._propagateFrom(castValue, 1); - } else { - promise._fulfillUnchecked(x); - } - } -}; - -Promise.prototype._follow = -function Promise$_follow(promise) { - this._setFollowing(); - - if (promise.isPending()) { - this._propagateFrom(promise, 1); - promise._proxyPromise(this); - } else if (promise.isFulfilled()) { - this._fulfillUnchecked(promise._settledValue); - } else { - this._rejectUnchecked(promise._settledValue, - promise._getCarriedStackTrace()); - } - - if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled(); - - if (debugging && - promise._traceParent == null) { - promise._traceParent = this; - } -}; - -Promise.prototype._tryFollow = -function Promise$_tryFollow(value) { - if (this._isFollowingOrFulfilledOrRejected() || - value === this) { - return false; - } - var maybePromise = cast(value, void 0); - if (!(maybePromise instanceof Promise)) { - return false; - } - this._follow(maybePromise); - return true; -}; - -Promise.prototype._resetTrace = function Promise$_resetTrace() { - if (debugging) { - this._trace = new CapturedTrace(this._peekContext() === void 0); - } -}; - -Promise.prototype._setTrace = function Promise$_setTrace(parent) { - if (debugging) { - var context = this._peekContext(); - this._traceParent = context; - var isTopLevel = context === void 0; - if (parent !== void 0 && - parent._traceParent === context) { - this._trace = parent._trace; - } else { - this._trace = new CapturedTrace(isTopLevel); - } - } - return this; -}; - -Promise.prototype._attachExtraTrace = -function Promise$_attachExtraTrace(error) { - if (debugging) { - var promise = this; - var stack = error.stack; - stack = typeof stack === "string" ? stack.split("\n") : []; - CapturedTrace.protectErrorMessageNewlines(stack); - var headerLineCount = 1; - var combinedTraces = 1; - while(promise != null && - promise._trace != null) { - stack = CapturedTrace.combine( - stack, - promise._trace.stack.split("\n") - ); - promise = promise._traceParent; - combinedTraces++; - } - - var stackTraceLimit = Error.stackTraceLimit || 10; - var max = (stackTraceLimit + headerLineCount) * combinedTraces; - var len = stack.length; - if (len > max) { - stack.length = max; - } - - if (len > 0) - stack[0] = stack[0].split("\u0002\u0000\u0001").join("\n"); - - if (stack.length <= headerLineCount) { - error.stack = "(No stack trace)"; - } else { - error.stack = stack.join("\n"); - } - } -}; - -Promise.prototype._cleanValues = function Promise$_cleanValues() { - if (this._cancellable()) { - this._cancellationParent = void 0; - } -}; - -Promise.prototype._propagateFrom = -function Promise$_propagateFrom(parent, flags) { - if ((flags & 1) > 0 && parent._cancellable()) { - this._setCancellable(); - this._cancellationParent = parent; - } - if ((flags & 4) > 0) { - this._setBoundTo(parent._boundTo); - } - if ((flags & 2) > 0) { - this._setTrace(parent); - } -}; - -Promise.prototype._fulfill = function Promise$_fulfill(value) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._fulfillUnchecked(value); -}; - -Promise.prototype._reject = -function Promise$_reject(reason, carriedStackTrace) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._rejectUnchecked(reason, carriedStackTrace); -}; - -Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) { - var handler = this.isFulfilled() - ? this._fulfillmentHandlerAt(index) - : this._rejectionHandlerAt(index); - - var value = this._settledValue; - var receiver = this._receiverAt(index); - var promise = this._promiseAt(index); - - if (typeof handler === "function") { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } else { - var done = false; - var isFulfilled = this.isFulfilled(); - if (receiver !== void 0) { - if (receiver instanceof Promise && - receiver._isProxied()) { - receiver._unsetProxied(); - - if (isFulfilled) receiver._fulfillUnchecked(value); - else receiver._rejectUnchecked(value, - this._getCarriedStackTrace()); - done = true; - } else if (receiver instanceof PromiseArray) { - if (isFulfilled) receiver._promiseFulfilled(value, promise); - else receiver._promiseRejected(value, promise); - done = true; - } - } - - if (!done) { - if (isFulfilled) promise._fulfill(value); - else promise._reject(value, this._getCarriedStackTrace()); - } - } - - if (index >= 4) { - this._queueGC(); - } -}; - -Promise.prototype._isProxied = function Promise$_isProxied() { - return (this._bitField & 4194304) === 4194304; -}; - -Promise.prototype._setProxied = function Promise$_setProxied() { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._unsetProxied = function Promise$_unsetProxied() { - this._bitField = this._bitField & (~4194304); -}; - -Promise.prototype._isGcQueued = function Promise$_isGcQueued() { - return (this._bitField & -1073741824) === -1073741824; -}; - -Promise.prototype._setGcQueued = function Promise$_setGcQueued() { - this._bitField = this._bitField | -1073741824; -}; - -Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() { - this._bitField = this._bitField & (~-1073741824); -}; - -Promise.prototype._queueGC = function Promise$_queueGC() { - if (this._isGcQueued()) return; - this._setGcQueued(); - async.invokeLater(this._gc, this, void 0); -}; - -Promise.prototype._gc = function Promise$gc() { - var len = this._length() * 5 - 5; - for (var i = 0; i < len; i++) { - delete this[i]; - } - this._clearFirstHandlerData(); - this._setLength(0); - this._unsetGcQueued(); -}; - -Promise.prototype._clearFirstHandlerData = -function Promise$_clearFirstHandlerData() { - this._fulfillmentHandler0 = void 0; - this._rejectionHandler0 = void 0; - this._promise0 = void 0; - this._receiver0 = void 0; -}; - -Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) { - if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); - async.invoke(this._settlePromiseAt, this, index); -}; - -Promise.prototype._fulfillUnchecked = -function Promise$_fulfillUnchecked(value) { - if (!this.isPending()) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err, void 0); - } - this._cleanValues(); - this._setFulfilled(); - this._settledValue = value; - var len = this._length(); - - if (len > 0) { - async.invoke(this._settlePromises, this, len); - } -}; - -Promise.prototype._rejectUncheckedCheckError = -function Promise$_rejectUncheckedCheckError(reason) { - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._rejectUnchecked(reason, trace === reason ? void 0 : trace); -}; - -Promise.prototype._rejectUnchecked = -function Promise$_rejectUnchecked(reason, trace) { - if (!this.isPending()) return; - if (reason === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err); - } - this._cleanValues(); - this._setRejected(); - this._settledValue = reason; - - if (this._isFinal()) { - async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace); - return; - } - var len = this._length(); - - if (trace !== void 0) this._setCarriedStackTrace(trace); - - if (len > 0) { - async.invoke(this._rejectPromises, this, null); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._rejectPromises = function Promise$_rejectPromises() { - this._settlePromises(); - this._unsetCarriedStackTrace(); -}; - -Promise.prototype._settlePromises = function Promise$_settlePromises() { - var len = this._length(); - for (var i = 0; i < len; i++) { - this._settlePromiseAt(i); - } -}; - -Promise.prototype._ensurePossibleRejectionHandled = -function Promise$_ensurePossibleRejectionHandled() { - this._setRejectionIsUnhandled(); - if (CapturedTrace.possiblyUnhandledRejection !== void 0) { - async.invokeLater(this._notifyUnhandledRejection, this, void 0); - } -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = -function Promise$_notifyUnhandledRejectionIsHandled() { - if (typeof unhandledRejectionHandled === "function") { - async.invokeLater(unhandledRejectionHandled, void 0, this); - } -}; - -Promise.prototype._notifyUnhandledRejection = -function Promise$_notifyUnhandledRejection() { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue; - var trace = this._getCarriedStackTrace(); - - this._setUnhandledRejectionIsNotified(); - - if (trace !== void 0) { - this._unsetCarriedStackTrace(); - reason = trace; - } - if (typeof CapturedTrace.possiblyUnhandledRejection === "function") { - CapturedTrace.possiblyUnhandledRejection(reason, this); - } - } -}; - -var contextStack = []; -Promise.prototype._peekContext = function Promise$_peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return void 0; - -}; - -Promise.prototype._pushContext = function Promise$_pushContext() { - if (!debugging) return; - contextStack.push(this); -}; - -Promise.prototype._popContext = function Promise$_popContext() { - if (!debugging) return; - contextStack.pop(); -}; - -Promise.noConflict = function Promise$NoConflict() { - return noConflict(Promise); -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function"); - async._schedule = fn; -}; - -if (!CapturedTrace.isSupported()) { - Promise.longStackTraces = function(){}; - debugging = false; -} - -Promise._makeSelfResolutionError = makeSelfResolutionError; -require("./finally.js")(Promise, NEXT_FILTER, cast); -require("./direct_resolve.js")(Promise); -require("./synchronous_inspection.js")(Promise); -require("./join.js")(Promise, PromiseArray, cast, INTERNAL); -Promise.RangeError = RangeError; -Promise.CancellationError = CancellationError; -Promise.TimeoutError = TimeoutError; -Promise.TypeError = TypeError; -Promise.OperationalError = OperationalError; -Promise.RejectionError = OperationalError; -Promise.AggregateError = errors.AggregateError; - -util.toFastProperties(Promise); -util.toFastProperties(Promise.prototype); -Promise.Promise = Promise; -require('./timers.js')(Promise,INTERNAL,cast); -require('./race.js')(Promise,INTERNAL,cast); -require('./call_get.js')(Promise); -require('./generators.js')(Promise,apiRejection,INTERNAL,cast); -require('./map.js')(Promise,PromiseArray,apiRejection,cast,INTERNAL); -require('./nodeify.js')(Promise); -require('./promisify.js')(Promise,INTERNAL); -require('./props.js')(Promise,PromiseArray,cast); -require('./reduce.js')(Promise,PromiseArray,apiRejection,cast,INTERNAL); -require('./settle.js')(Promise,PromiseArray); -require('./some.js')(Promise,PromiseArray,apiRejection); -require('./progress.js')(Promise,PromiseArray); -require('./cancel.js')(Promise,INTERNAL); -require('./filter.js')(Promise,INTERNAL); -require('./any.js')(Promise,PromiseArray); -require('./each.js')(Promise,INTERNAL); -require('./using.js')(Promise,apiRejection,cast); - -Promise.prototype = Promise.prototype; -return Promise; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js deleted file mode 100644 index db85c8a..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_array.js +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, cast) { -var canAttach = require("./errors.js").canAttach; -var util = require("./util.js"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -1: return void 0; - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - var parent = void 0; - if (values instanceof Promise) { - parent = values; - promise._propagateFrom(parent, 1 | 4); - } - promise._setTrace(parent); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(void 0, -2); -} -PromiseArray.prototype.length = function PromiseArray$length() { - return this._length; -}; - -PromiseArray.prototype.promise = function PromiseArray$promise() { - return this._promise; -}; - -PromiseArray.prototype._init = -function PromiseArray$_init(_, resolveValueIfEmpty) { - var values = cast(this._values, void 0); - if (values instanceof Promise) { - this._values = values; - values._setBoundTo(this._promise._boundTo); - if (values.isFulfilled()) { - values = values._settledValue; - if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable"); - this.__hardReject__(err); - return; - } - } else if (values.isPending()) { - values._then( - PromiseArray$_init, - this._reject, - void 0, - this, - resolveValueIfEmpty - ); - return; - } else { - values._unsetRejectionIsUnhandled(); - this._reject(values._settledValue); - return; - } - } else if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable"); - this.__hardReject__(err); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - var len = this.getActualLength(values.length); - var newLen = len; - var newValues = this.shouldCopyValues() ? new Array(len) : this._values; - var isDirectScanNeeded = false; - for (var i = 0; i < len; ++i) { - var maybePromise = cast(values[i], void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, i); - } else { - maybePromise._unsetRejectionIsUnhandled(); - isDirectScanNeeded = true; - } - } else { - isDirectScanNeeded = true; - } - newValues[i] = maybePromise; - } - this._values = newValues; - this._length = newLen; - if (isDirectScanNeeded) { - this._scanDirectValues(len); - } -}; - -PromiseArray.prototype._settlePromiseAt = -function PromiseArray$_settlePromiseAt(index) { - var value = this._values[index]; - if (!(value instanceof Promise)) { - this._promiseFulfilled(value, index); - } else if (value.isFulfilled()) { - this._promiseFulfilled(value._settledValue, index); - } else if (value.isRejected()) { - this._promiseRejected(value._settledValue, index); - } -}; - -PromiseArray.prototype._scanDirectValues = -function PromiseArray$_scanDirectValues(len) { - for (var i = 0; i < len; ++i) { - if (this._isResolved()) { - break; - } - this._settlePromiseAt(i); - } -}; - -PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype.__hardReject__ = -PromiseArray.prototype._reject = function PromiseArray$_reject(reason) { - this._values = null; - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(reason, trace); -}; - -PromiseArray.prototype._promiseProgressed = -function PromiseArray$_promiseProgressed(progressValue, index) { - if (this._isResolved()) return; - this._promise._progress({ - index: index, - value: progressValue - }); -}; - - -PromiseArray.prototype._promiseFulfilled = -function PromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -PromiseArray.prototype._promiseRejected = -function PromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; - this._totalResolved++; - this._reject(reason); -}; - -PromiseArray.prototype.shouldCopyValues = -function PromiseArray$_shouldCopyValues() { - return true; -}; - -PromiseArray.prototype.getActualLength = -function PromiseArray$getActualLength(len) { - return len; -}; - -return PromiseArray; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js deleted file mode 100644 index 103c04e..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/promise_resolver.js +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var util = require("./util.js"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors.js"); -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var async = require("./async.js"); -var haveGetters = util.haveGetters; -var es5 = require("./es5.js"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - } else { - ret = obj; - } - errors.markAsOriginatingFromRejection(ret); - return ret; -} - -function nodebackForPromise(promise) { - function PromiseResolver$_callback(err, value) { - if (promise === null) return; - - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (arguments.length > 2) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - promise._fulfill(args); - } else { - promise._fulfill(value); - } - - promise = null; - } - return PromiseResolver$_callback; -} - - -var PromiseResolver; -if (!haveGetters) { - PromiseResolver = function PromiseResolver(promise) { - this.promise = promise; - this.asCallback = nodebackForPromise(promise); - this.callback = this.asCallback; - }; -} -else { - PromiseResolver = function PromiseResolver(promise) { - this.promise = promise; - }; -} -if (haveGetters) { - var prop = { - get: function() { - return nodebackForPromise(this.promise); - } - }; - es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); - es5.defineProperty(PromiseResolver.prototype, "callback", prop); -} - -PromiseResolver._nodebackForPromise = nodebackForPromise; - -PromiseResolver.prototype.toString = function PromiseResolver$toString() { - return "[object PromiseResolver]"; -}; - -PromiseResolver.prototype.resolve = -PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - - var promise = this.promise; - if (promise._tryFollow(value)) { - return; - } - async.invoke(promise._fulfill, promise, value); -}; - -PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - - var promise = this.promise; - errors.markAsOriginatingFromRejection(reason); - var trace = errors.canAttach(reason) ? reason : new Error(reason + ""); - promise._attachExtraTrace(trace); - async.invoke(promise._reject, promise, reason); - if (trace !== reason) { - async.invoke(this._setCarriedStackTrace, this, trace); - } -}; - -PromiseResolver.prototype.progress = -function PromiseResolver$progress(value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - async.invoke(this.promise._progress, this.promise, value); -}; - -PromiseResolver.prototype.cancel = function PromiseResolver$cancel() { - async.invoke(this.promise.cancel, this.promise, void 0); -}; - -PromiseResolver.prototype.timeout = function PromiseResolver$timeout() { - this.reject(new TimeoutError("timeout")); -}; - -PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() { - return this.promise.isResolved(); -}; - -PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() { - return this.promise.toJSON(); -}; - -PromiseResolver.prototype._setCarriedStackTrace = -function PromiseResolver$_setCarriedStackTrace(trace) { - if (this.promise.isRejected()) { - this.promise._setCarriedStackTrace(trace); - } -}; - -module.exports = PromiseResolver; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js deleted file mode 100644 index 9da9859..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/props.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, cast) { -var util = require("./util.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var isObject = util.isObject; -var es5 = require("./es5.js"); - -function PropertiesPromiseArray(obj) { - var keys = es5.keys(obj); - var len = keys.length; - var values = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - values[i] = obj[key]; - values[i + len] = key; - } - this.constructor$(values); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = -function PropertiesPromiseArray$_init() { - this._init$(void 0, -3) ; -}; - -PropertiesPromiseArray.prototype._promiseFulfilled = -function PropertiesPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - this._resolve(val); - } -}; - -PropertiesPromiseArray.prototype._promiseProgressed = -function PropertiesPromiseArray$_promiseProgressed(value, index) { - if (this._isResolved()) return; - - this._promise._progress({ - key: this._values[index + this.length()], - value: value - }); -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = -function PropertiesPromiseArray$_shouldCopyValues() { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = -function PropertiesPromiseArray$getActualLength(len) { - return len >> 1; -}; - -function Promise$_Props(promises) { - var ret; - var castValue = cast(promises, void 0); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object"); - } else if (castValue instanceof Promise) { - ret = castValue._then(Promise.props, void 0, void 0, void 0, void 0); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 4); - } - return ret; -} - -Promise.prototype.props = function Promise$props() { - return Promise$_Props(this); -}; - -Promise.props = function Promise$Props(promises) { - return Promise$_Props(promises); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js deleted file mode 100644 index d3dccdd..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/queue.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -function arrayCopy(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; - this._makeCapacity(); -} - -Queue.prototype._willBeOverCapacity = -function Queue$_willBeOverCapacity(size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function Queue$_pushOne(arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype.push = function Queue$push(fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function Queue$shift() { - var front = this._front, - ret = this[front]; - - this[front] = void 0; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function Queue$length() { - return this._length; -}; - -Queue.prototype._makeCapacity = function Queue$_makeCapacity() { - var len = this._capacity; - for (var i = 0; i < len; ++i) { - this[i] = void 0; - } -}; - -Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 3); - } -}; - -Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) { - var oldFront = this._front; - var oldCapacity = this._capacity; - var oldQueue = new Array(oldCapacity); - var length = this.length(); - - arrayCopy(this, 0, oldQueue, 0, oldCapacity); - this._capacity = capacity; - this._makeCapacity(); - this._front = 0; - if (oldFront + length <= oldCapacity) { - arrayCopy(oldQueue, oldFront, this, 0, length); - } else { var lengthBeforeWrapping = - length - ((oldFront + length) & (oldCapacity - 1)); - - arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping); - arrayCopy(oldQueue, 0, this, lengthBeforeWrapping, - length - lengthBeforeWrapping); - } -}; - -module.exports = Queue; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js deleted file mode 100644 index 4e4c30e..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/race.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, cast) { -var apiRejection = require("./errors_api_rejection.js")(Promise); -var isArray = require("./util.js").isArray; - -var raceLater = function Promise$_raceLater(promise) { - return promise.then(function(array) { - return Promise$_Race(array, promise); - }); -}; - -var hasOwn = {}.hasOwnProperty; -function Promise$_Race(promises, parent) { - var maybePromise = cast(promises, void 0); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else if (!isArray(promises)) { - return apiRejection("expecting an array, a promise or a thenable"); - } - - var ret = new Promise(INTERNAL); - if (parent !== void 0) { - ret._propagateFrom(parent, 7); - } else { - ret._setTrace(void 0); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === void 0 && !(hasOwn.call(promises, i))) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, void 0, ret, null); - } - return ret; -} - -Promise.race = function Promise$Race(promises) { - return Promise$_Race(promises, void 0); -}; - -Promise.prototype.race = function Promise$race() { - return Promise$_Race(this, void 0); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js deleted file mode 100644 index 30f2f05..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/reduce.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, cast, INTERNAL) { -var util = require("./util.js"); -var tryCatch4 = util.tryCatch4; -var tryCatch3 = util.tryCatch3; -var errorObj = util.errorObj; -function ReductionPromiseArray(promises, fn, accum, _each) { - this.constructor$(promises); - this._preservedValues = _each === INTERNAL ? [] : null; - this._zerothIsAccum = (accum === void 0); - this._gotAccum = false; - this._reducingIndex = (this._zerothIsAccum ? 1 : 0); - this._valuesPhase = undefined; - - var maybePromise = cast(accum, void 0); - var rejected = false; - var isPromise = maybePromise instanceof Promise; - if (isPromise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, -1); - } else if (maybePromise.isFulfilled()) { - accum = maybePromise.value(); - this._gotAccum = true; - } else { - maybePromise._unsetRejectionIsUnhandled(); - this._reject(maybePromise.reason()); - rejected = true; - } - } - if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; - this._callback = fn; - this._accum = accum; - if (!rejected) this._init$(void 0, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._init = -function ReductionPromiseArray$_init() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = -function ReductionPromiseArray$_resolveEmptyArray() { - if (this._gotAccum || this._zerothIsAccum) { - this._resolve(this._preservedValues !== null - ? [] : this._accum); - } -}; - -ReductionPromiseArray.prototype._promiseFulfilled = -function ReductionPromiseArray$_promiseFulfilled(value, index) { - var values = this._values; - if (values === null) return; - var length = this.length(); - var preservedValues = this._preservedValues; - var isEach = preservedValues !== null; - var gotAccum = this._gotAccum; - var valuesPhase = this._valuesPhase; - var valuesPhaseIndex; - if (!valuesPhase) { - valuesPhase = this._valuesPhase = Array(length); - for (valuesPhaseIndex=0; valuesPhaseIndex - * - * 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. - * - */ -"use strict"; -var schedule; -var _MutationObserver; -if (typeof process === "object" && typeof process.version === "string") { - schedule = function Promise$_Scheduler(fn) { - process.nextTick(fn); - }; -} -else if ((typeof MutationObserver !== "undefined" && - (_MutationObserver = MutationObserver)) || - (typeof WebKitMutationObserver !== "undefined" && - (_MutationObserver = WebKitMutationObserver))) { - schedule = (function() { - var div = document.createElement("div"); - var queuedFn = void 0; - var observer = new _MutationObserver( - function Promise$_Scheduler() { - var fn = queuedFn; - queuedFn = void 0; - fn(); - } - ); - observer.observe(div, { - attributes: true - }); - return function Promise$_Scheduler(fn) { - queuedFn = fn; - div.classList.toggle("foo"); - }; - - })(); -} -else if (typeof setTimeout !== "undefined") { - schedule = function Promise$_Scheduler(fn) { - setTimeout(fn, 0); - }; -} -else throw new Error("no async scheduler available"); -module.exports = schedule; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js deleted file mode 100644 index 9881297..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/settle.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = - function(Promise, PromiseArray) { -var PromiseInspection = Promise.PromiseInspection; -var util = require("./util.js"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = -function SettledPromiseArray$_promiseResolved(index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -SettledPromiseArray.prototype._promiseFulfilled = -function SettledPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - var ret = new PromiseInspection(); - ret._bitField = 268435456; - ret._settledValue = value; - this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = -function SettledPromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; - var ret = new PromiseInspection(); - ret._bitField = 134217728; - ret._settledValue = reason; - this._promiseResolved(index, ret); -}; - -Promise.settle = function Promise$Settle(promises) { - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function Promise$settle() { - return new SettledPromiseArray(this).promise(); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js deleted file mode 100644 index dba7183..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/some.js +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = require("./util.js"); -var RangeError = require("./errors.js").RangeError; -var AggregateError = require("./errors.js").AggregateError; -var isArray = util.isArray; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function SomePromiseArray$_init() { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(void 0, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function SomePromiseArray$init() { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = -function SomePromiseArray$setHowMany(count) { - if (this._isResolved()) return; - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = -function SomePromiseArray$_promiseFulfilled(value) { - if (this._isResolved()) return; - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - } - -}; -SomePromiseArray.prototype._promiseRejected = -function SomePromiseArray$_promiseRejected(reason) { - if (this._isResolved()) return; - this._addRejected(reason); - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - e.push(this._values[i]); - } - this._reject(e); - } -}; - -SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = -function SomePromiseArray$_addRejected(reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = -function SomePromiseArray$_addFulfilled(value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = -function SomePromiseArray$_canPossiblyFulfill() { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = -function SomePromiseArray$_getRangeError(count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = -function SomePromiseArray$_resolveEmptyArray() { - this._reject(this._getRangeError(0)); -}; - -function Promise$_Some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function Promise$Some(promises, howMany) { - return Promise$_Some(promises, howMany); -}; - -Promise.prototype.some = function Promise$some(howMany) { - return Promise$_Some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js deleted file mode 100644 index 3c84020..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/synchronous_inspection.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== void 0) { - this._bitField = promise._bitField; - this._settledValue = promise.isResolved() - ? promise._settledValue - : void 0; - } - else { - this._bitField = 0; - this._settledValue = void 0; - } -} - -PromiseInspection.prototype.isFulfilled = -Promise.prototype.isFulfilled = function Promise$isFulfilled() { - return (this._bitField & 268435456) > 0; -}; - -PromiseInspection.prototype.isRejected = -Promise.prototype.isRejected = function Promise$isRejected() { - return (this._bitField & 134217728) > 0; -}; - -PromiseInspection.prototype.isPending = -Promise.prototype.isPending = function Promise$isPending() { - return (this._bitField & 402653184) === 0; -}; - -PromiseInspection.prototype.value = -Promise.prototype.value = function Promise$value() { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = -Promise.prototype.reason = function Promise$reason() { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.isResolved = -Promise.prototype.isResolved = function Promise$isResolved() { - return (this._bitField & 402653184) > 0; -}; - -Promise.PromiseInspection = PromiseInspection; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js deleted file mode 100644 index 09e0266..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/thenables.js +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = require("./util.js"); -var canAttach = require("./errors.js").canAttach; -var errorObj = util.errorObj; -var isObject = util.isObject; - -function getThen(obj) { - try { - return obj.then; - } - catch(e) { - errorObj.e = e; - return errorObj; - } -} - -function Promise$_Cast(obj, originalPromise) { - if (isObject(obj)) { - if (obj instanceof Promise) { - return obj; - } - else if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - obj._then( - ret._fulfillUnchecked, - ret._rejectUncheckedCheckError, - ret._progressUnchecked, - ret, - null - ); - ret._setFollowing(); - return ret; - } - var then = getThen(obj); - if (then === errorObj) { - if (originalPromise !== void 0 && canAttach(then.e)) { - originalPromise._attachExtraTrace(then.e); - } - return Promise.reject(then.e); - } else if (typeof then === "function") { - return Promise$_doThenable(obj, then, originalPromise); - } - } - return obj; -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - return hasProp.call(obj, "_promise0"); -} - -function Promise$_doThenable(x, then, originalPromise) { - var resolver = Promise.defer(); - var called = false; - try { - then.call( - x, - Promise$_resolveFromThenable, - Promise$_rejectFromThenable, - Promise$_progressFromThenable - ); - } catch(e) { - if (!called) { - called = true; - var trace = canAttach(e) ? e : new Error(e + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); - } - resolver.promise._reject(e, trace); - } - } - return resolver.promise; - - function Promise$_resolveFromThenable(y) { - if (called) return; - called = true; - - if (x === y) { - var e = Promise._makeSelfResolutionError(); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(e); - } - resolver.promise._reject(e, void 0); - return; - } - resolver.resolve(y); - } - - function Promise$_rejectFromThenable(r) { - if (called) return; - called = true; - var trace = canAttach(r) ? r : new Error(r + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); - } - resolver.promise._reject(r, trace); - } - - function Promise$_progressFromThenable(v) { - if (called) return; - var promise = resolver.promise; - if (typeof promise._progress === "function") { - promise._progress(v); - } - } -} - -return Promise$_Cast; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js deleted file mode 100644 index 2d35221..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/timers.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var _setTimeout = function(fn, ms) { - var len = arguments.length; - var arg0 = arguments[2]; - var arg1 = arguments[3]; - var arg2 = len >= 5 ? arguments[4] : void 0; - setTimeout(function() { - fn(arg0, arg1, arg2); - }, ms|0); -}; - -module.exports = function(Promise, INTERNAL, cast) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var TimeoutError = Promise.TimeoutError; - -var afterTimeout = function Promise$_afterTimeout(promise, message, ms) { - if (!promise.isPending()) return; - if (typeof message !== "string") { - message = "operation timed out after" + " " + ms + " ms" - } - var err = new TimeoutError(message); - errors.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._cancel(err); -}; - -var afterDelay = function Promise$_afterDelay(value, promise) { - promise._fulfill(value); -}; - -var delay = Promise.delay = function Promise$Delay(value, ms) { - if (ms === void 0) { - ms = value; - value = void 0; - } - ms = +ms; - var maybePromise = cast(value, void 0); - var promise = new Promise(INTERNAL); - - if (maybePromise instanceof Promise) { - promise._propagateFrom(maybePromise, 7); - promise._follow(maybePromise); - return promise.then(function(value) { - return Promise.delay(value, ms); - }); - } else { - promise._setTrace(void 0); - _setTimeout(afterDelay, ms, value, promise); - } - return promise; -}; - -Promise.prototype.delay = function Promise$delay(ms) { - return delay(this, ms); -}; - -Promise.prototype.timeout = function Promise$timeout(ms, message) { - ms = +ms; - - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 7); - ret._follow(this); - _setTimeout(afterTimeout, ms, ret, message, ms); - return ret.cancellable(); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js deleted file mode 100644 index 9ade965..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/using.js +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function (Promise, apiRejection, cast) { - var TypeError = require("./errors.js").TypeError; - var inherits = require("./util.js").inherits; - var PromiseInspection = Promise.PromiseInspection; - - function inspectionMapper(inspections) { - var len = inspections.length; - for (var i = 0; i < len; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - return Promise.reject(inspection.error()); - } - inspections[i] = inspection.value(); - } - return inspections; - } - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = cast(thenable, void 0); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = Promise.defer(); - function iterator() { - if (i >= len) return ret.resolve(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = cast(maybePromise._getDisposer() - .tryDispose(inspection), void 0); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret.promise; - } - - function disposerSuccess(value) { - var inspection = new PromiseInspection(); - inspection._settledValue = value; - inspection._bitField = 268435456; - return dispose(this, inspection).thenReturn(value); - } - - function disposerFail(reason) { - var inspection = new PromiseInspection(); - inspection._settledValue = reason; - inspection._bitField = 134217728; - return dispose(this, inspection).thenThrow(reason); - } - - function Disposer(data, promise) { - this._data = data; - this._promise = promise; - } - - Disposer.prototype.data = function Disposer$data() { - return this._data; - }; - - Disposer.prototype.promise = function Disposer$promise() { - return this._promise; - }; - - Disposer.prototype.resource = function Disposer$resource() { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return null; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var ret = resource !== null - ? this.doDispose(resource, inspection) : null; - this._promise._unsetDisposable(); - this._data = this._promise = null; - return ret; - }; - - Disposer.isDisposer = function Disposer$isDisposer(d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise) { - this.constructor$(fn, promise); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - Promise.using = function Promise$using() { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") return apiRejection("fn must be a function"); - len--; - var resources = new Array(len); - for (var i = 0; i < len; ++i) { - var resource = arguments[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } - resources[i] = resource; - } - - return Promise.settle(resources) - .then(inspectionMapper) - .spread(fn) - ._then(disposerSuccess, disposerFail, void 0, resources, void 0); - }; - - Promise.prototype._setDisposable = - function Promise$_setDisposable(disposer) { - this._bitField = this._bitField | 262144; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function Promise$_isDisposable() { - return (this._bitField & 262144) > 0; - }; - - Promise.prototype._getDisposer = function Promise$_getDisposer() { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function Promise$_unsetDisposable() { - this._bitField = this._bitField & (~262144); - this._disposer = void 0; - }; - - Promise.prototype.disposer = function Promise$disposer(fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this); - } - throw new TypeError(); - }; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js deleted file mode 100644 index 0fadbc3..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/main/util.js +++ /dev/null @@ -1,268 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var es5 = require("./es5.js"); -var haveGetters = (function(){ - try { - var o = {}; - es5.defineProperty(o, "f", { - get: function () { - return 3; - } - }); - return o.f === 3; - } - catch (e) { - return false; - } - -})(); -var canEvaluate = typeof navigator == "undefined"; -var errorObj = {e: {}}; -function tryCatch1(fn, receiver, arg) { - try { return fn.call(receiver, arg); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch2(fn, receiver, arg, arg2) { - try { return fn.call(receiver, arg, arg2); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch3(fn, receiver, arg, arg2, arg3) { - try { return fn.call(receiver, arg, arg2, arg3); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch4(fn, receiver, arg, arg2, arg3, arg4) { - try { return fn.call(receiver, arg, arg2, arg3, arg4); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatchApply(fn, args, receiver) { - try { return fn.apply(receiver, args); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - -function asString(val) { - return typeof val === "string" ? val : ("" + val); -} - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return !isPrimitive(value); -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(asString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : void 0; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - - -var wrapsPrimitiveReceiver = (function() { - return this !== "string"; -}).call("string"); - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - if (es5.isES5) { - return function(obj, opts) { - var ret = []; - var visitedKeys = Object.create(null); - var getKeys = Object(opts).includeHidden - ? Object.getOwnPropertyNames - : Object.keys; - while (obj != null) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - return function(obj) { - var ret = []; - /*jshint forin:false */ - for (var key in obj) { - ret.push(key); - } - return ret; - }; - } - -})(); - -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.keys(fn.prototype); - return keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027*/ - function f() {} - f.prototype = obj; - return f; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - haveGetters: haveGetters, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch1: tryCatch1, - tryCatch2: tryCatch2, - tryCatch3: tryCatch3, - tryCatch4: tryCatch4, - tryCatchApply: tryCatchApply, - inherits: inherits, - withAppended: withAppended, - asString: asString, - maybeWrapAsError: maybeWrapAsError, - wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, - toFastProperties: toFastProperties, - filledRange: filledRange -}; - -module.exports = ret; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/any.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/any.js deleted file mode 100644 index 75d1de1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/any.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -function Promise$_Any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} - -Promise.any = function Promise$Any(promises) { - return Promise$_Any(promises); -}; - -Promise.prototype.any = function Promise$any() { - return Promise$_Any(this); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/assert.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/assert.js deleted file mode 100644 index 86ac49e..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/assert.js +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = (function(){ -var AssertionError = (function() { - function AssertionError(a) { - this.constructor$(a); - this.message = a; - this.name = "AssertionError"; - } - AssertionError.prototype = new Error(); - AssertionError.prototype.constructor = AssertionError; - AssertionError.prototype.constructor$ = Error; - return AssertionError; -})(); - -function getParams(args) { - var params = []; - for (var i = 0; i < args.length; ++i) params.push("arg" + i); - return params; -} - -function nativeAssert(callName, args, expect) { - try { - var params = getParams(args); - var constructorArgs = params; - constructorArgs.push("return " + - callName + "("+ params.join(",") + ");"); - var fn = Function.apply(null, constructorArgs); - return fn.apply(null, args); - } catch (e) { - if (!(e instanceof SyntaxError)) { - throw e; - } else { - return expect; - } - } -} - -return function assert(boolExpr, message) { - if (boolExpr === true) return; - - if (typeof boolExpr === "string" && - boolExpr.charAt(0) === "%") { - var nativeCallName = boolExpr; - var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} - if (nativeAssert(nativeCallName, args, message) === message) return; - message = (nativeCallName + " !== " + message); - } - - var ret = new AssertionError(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(ret, assert); - } - if (console && console.error) { - console.error(ret.stack + ""); - } - throw ret; - -}; -})(); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/async.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/async.js deleted file mode 100644 index 50004c9..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/async.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var schedule = require("./schedule.js"); -var Queue = require("./queue.js"); -var errorObj = require("./util.js").errorObj; -var tryCatch1 = require("./util.js").tryCatch1; -var _process = typeof process !== "undefined" ? process : void 0; - -function Async() { - this._isTickUsed = false; - this._schedule = schedule; - this._length = 0; - this._lateBuffer = new Queue(16); - this._functionBuffer = new Queue(65536); - var self = this; - this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() { - self._consumeFunctionBuffer(); - }; -} - -Async.prototype.haveItemsQueued = function Async$haveItemsQueued() { - return this._length > 0; -}; - -Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) { - if (_process !== void 0 && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - this._lateBuffer.push(fn, receiver, arg); - this._queueTick(); -}; - -Async.prototype.invoke = function Async$invoke(fn, receiver, arg) { - if (_process !== void 0 && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - var functionBuffer = this._functionBuffer; - functionBuffer.push(fn, receiver, arg); - this._length = functionBuffer.length(); - this._queueTick(); -}; - -Async.prototype._consumeFunctionBuffer = -function Async$_consumeFunctionBuffer() { - var functionBuffer = this._functionBuffer; - while (functionBuffer.length() > 0) { - var fn = functionBuffer.shift(); - var receiver = functionBuffer.shift(); - var arg = functionBuffer.shift(); - fn.call(receiver, arg); - } - this._reset(); - this._consumeLateBuffer(); -}; - -Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() { - var buffer = this._lateBuffer; - while(buffer.length() > 0) { - var fn = buffer.shift(); - var receiver = buffer.shift(); - var arg = buffer.shift(); - var res = tryCatch1(fn, receiver, arg); - if (res === errorObj) { - this._queueTick(); - if (fn.domain != null) { - fn.domain.emit("error", res.e); - } else { - throw res.e; - } - } - } -}; - -Async.prototype._queueTick = function Async$_queue() { - if (!this._isTickUsed) { - this._schedule(this.consumeFunctionBuffer); - this._isTickUsed = true; - } -}; - -Async.prototype._reset = function Async$_reset() { - this._isTickUsed = false; - this._length = 0; -}; - -module.exports = new Async(); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/bluebird.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/bluebird.js deleted file mode 100644 index 6fd85f1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/bluebird.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var Promise = require("./promise.js")(); -module.exports = Promise; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/call_get.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/call_get.js deleted file mode 100644 index dfaaf5c..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/call_get.js +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -function makeMethodCaller (methodName) { - return new Function("obj", " \n\ - 'use strict' \n\ - var len = this.length; \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: return obj.methodName.apply(obj, this); \n\ - } \n\ - ".replace(/methodName/g, methodName)); -} - -function makeGetter (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -} - -function getCompiled(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -} - -function getMethodCaller(name) { - return getCompiled(name, makeMethodCaller, callerCache); -} - -function getGetter(name) { - return getCompiled(name, makeGetter, getterCache); -} - -function caller(obj) { - return obj[this.pop()].apply(obj, this); -} -Promise.prototype.call = function Promise$call(methodName) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then(maybeCaller, void 0, void 0, args, void 0); - } - } - args.push(methodName); - return this._then(caller, void 0, void 0, args, void 0); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - return obj[this]; -} -Promise.prototype.get = function Promise$get(propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, void 0, void 0, propertyName, void 0); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/cancel.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/cancel.js deleted file mode 100644 index d3022b6..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/cancel.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var errors = require("./errors.js"); -var canAttach = errors.canAttach; -var async = require("./async.js"); -var CancellationError = errors.CancellationError; - -Promise.prototype._cancel = function Promise$_cancel(reason) { - if (!this.isCancellable()) return this; - var parent; - var promiseToReject = this; - while ((parent = promiseToReject._cancellationParent) !== void 0 && - parent.isCancellable()) { - promiseToReject = parent; - } - promiseToReject._attachExtraTrace(reason); - promiseToReject._rejectUnchecked(reason); -}; - -Promise.prototype.cancel = function Promise$cancel(reason) { - if (!this.isCancellable()) return this; - reason = reason !== void 0 - ? (canAttach(reason) ? reason : new Error(reason + "")) - : new CancellationError(); - async.invokeLater(this._cancel, this, reason); - return this; -}; - -Promise.prototype.cancellable = function Promise$cancellable() { - if (this._cancellable()) return this; - this._setCancellable(); - this._cancellationParent = void 0; - return this; -}; - -Promise.prototype.uncancellable = function Promise$uncancellable() { - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 2 | 4); - ret._follow(this); - ret._unsetCancellable(); - return ret; -}; - -Promise.prototype.fork = -function Promise$fork(didFulfill, didReject, didProgress) { - var ret = this._then(didFulfill, didReject, didProgress, - void 0, void 0); - - ret._setCancellable(); - ret._cancellationParent = void 0; - return ret; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/captured_trace.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/captured_trace.js deleted file mode 100644 index 89fa8ca..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/captured_trace.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function() { -var inherits = require("./util.js").inherits; -var defineProperty = require("./es5.js").defineProperty; - -var rignore = new RegExp( - "\\b(?:[a-zA-Z0-9.]+\\$_\\w+|" + - "tryCatch(?:1|2|3|4|Apply)|new \\w*PromiseArray|" + - "\\w*PromiseArray\\.\\w*PromiseArray|" + - "setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" + - "process._tickCallback|nextTick|Async\\$\\w+)\\b" -); - -var rtraceline = null; -var formatStack = null; - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj.toString(); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function CapturedTrace(ignoreUntil, isTopLevel) { - this.captureStackTrace(CapturedTrace, isTopLevel); - -} -inherits(CapturedTrace, Error); - -CapturedTrace.prototype.captureStackTrace = -function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) { - captureStackTrace(this, ignoreUntil, isTopLevel); -}; - -CapturedTrace.possiblyUnhandledRejection = -function CapturedTrace$PossiblyUnhandledRejection(reason) { - if (typeof console === "object") { - var message; - if (typeof reason === "object" || typeof reason === "function") { - var stack = reason.stack; - message = "Possibly unhandled " + formatStack(stack, reason); - } else { - message = "Possibly unhandled " + String(reason); - } - if (typeof console.error === "function" || - typeof console.error === "object") { - console.error(message); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -}; - -CapturedTrace.combine = function CapturedTrace$Combine(current, prev) { - var curLast = current.length - 1; - for (var i = prev.length - 1; i >= 0; --i) { - var line = prev[i]; - if (current[curLast] === line) { - current.pop(); - curLast--; - } else { - break; - } - } - - current.push("From previous event:"); - var lines = current.concat(prev); - - var ret = []; - - for (var i = 0, len = lines.length; i < len; ++i) { - - if (((rignore.test(lines[i]) && rtraceline.test(lines[i])) || - (i > 0 && !rtraceline.test(lines[i])) && - lines[i] !== "From previous event:") - ) { - continue; - } - ret.push(lines[i]); - } - return ret; -}; - -CapturedTrace.protectErrorMessageNewlines = function(stack) { - for (var i = 0; i < stack.length; ++i) { - if (rtraceline.test(stack[i])) { - break; - } - } - - if (i <= 1) return; - - var errorMessageLines = []; - for (var j = 0; j < i; ++j) { - errorMessageLines.push(stack.shift()); - } - stack.unshift(errorMessageLines.join("\u0002\u0000\u0001")); -}; - -CapturedTrace.isSupported = function CapturedTrace$IsSupported() { - return typeof captureStackTrace === "function"; -}; - -var captureStackTrace = (function stackDetection() { - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - rtraceline = /^\s*at\s*/; - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - - - }; - var captureStackTrace = Error.captureStackTrace; - return function CapturedTrace$_captureStackTrace( - receiver, ignoreUntil) { - captureStackTrace(receiver, ignoreUntil); - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - typeof "".startsWith === "function" && - (err.stack.startsWith("stackDetection@")) && - stackDetection.name === "stackDetection") { - - defineProperty(Error, "stackTraceLimit", { - writable: true, - enumerable: false, - configurable: false, - value: 25 - }); - rtraceline = /@/; - var rline = /[@\n]/; - - formatStack = function(stack, error) { - if (typeof stack === "string") { - return (error.name + ". " + error.message + "\n" + stack); - } - - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return function captureStackTrace(o) { - var stack = new Error().stack; - var split = stack.split(rline); - var len = split.length; - var ret = ""; - for (var i = 0; i < len; i += 2) { - ret += split[i]; - ret += "@"; - ret += split[i + 1]; - ret += "\n"; - } - o.stack = ret; - }; - } else { - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return null; - } -})(); - -return CapturedTrace; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/catch_filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/catch_filter.js deleted file mode 100644 index 25d9f73..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/catch_filter.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; -var keys = require("./es5.js").keys; -var TypeError = errors.TypeError; - -function CatchFilter(instances, callback, promise) { - this._instances = instances; - this._callback = callback; - this._promise = promise; -} - -function CatchFilter$_safePredicate(predicate, e) { - var safeObject = {}; - var retfilter = tryCatch1(predicate, safeObject, e); - - if (retfilter === errorObj) return retfilter; - - var safeKeys = keys(safeObject); - if (safeKeys.length) { - errorObj.e = new TypeError( - "Catch filter must inherit from Error " - + "or be a simple predicate function"); - return errorObj; - } - return retfilter; -} - -CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) { - var cb = this._callback; - var promise = this._promise; - var boundTo = promise._boundTo; - for (var i = 0, len = this._instances.length; i < len; ++i) { - var item = this._instances[i]; - var itemIsErrorType = item === Error || - (item != null && item.prototype instanceof Error); - - if (itemIsErrorType && e instanceof item) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } else if (typeof item === "function" && !itemIsErrorType) { - var shouldHandle = CatchFilter$_safePredicate(item, e); - if (shouldHandle === errorObj) { - var trace = errors.canAttach(errorObj.e) - ? errorObj.e - : new Error(errorObj.e + ""); - this._promise._attachExtraTrace(trace); - e = errorObj.e; - break; - } else if (shouldHandle) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } - } - } - NEXT_FILTER.e = e; - return NEXT_FILTER; -}; - -return CatchFilter; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/direct_resolve.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/direct_resolve.js deleted file mode 100644 index 3386a19..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/direct_resolve.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var util = require("./util.js"); -var isPrimitive = util.isPrimitive; -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; - -module.exports = function(Promise) { -var returner = function Promise$_returner() { - return this; -}; -var thrower = function Promise$_thrower() { - throw this; -}; - -var wrapper = function Promise$_wrapper(value, action) { - if (action === 1) { - return function Promise$_thrower() { - throw value; - }; - } else if (action === 2) { - return function Promise$_returner() { - return value; - }; - } -}; - - -Promise.prototype["return"] = -Promise.prototype.thenReturn = -function Promise$thenReturn(value) { - if (wrapsPrimitiveReceiver && isPrimitive(value)) { - return this._then( - wrapper(value, 2), - void 0, - void 0, - void 0, - void 0 - ); - } - return this._then(returner, void 0, void 0, value, void 0); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = -function Promise$thenThrow(reason) { - if (wrapsPrimitiveReceiver && isPrimitive(reason)) { - return this._then( - wrapper(reason, 1), - void 0, - void 0, - void 0, - void 0 - ); - } - return this._then(thrower, void 0, void 0, reason, void 0); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/each.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/each.js deleted file mode 100644 index c89a144..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/each.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; - -Promise.prototype.each = function Promise$each(fn) { - return PromiseReduce(this, fn, null, INTERNAL); -}; - -Promise.each = function Promise$Each(promises, fn) { - return PromiseReduce(promises, fn, null, INTERNAL); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors.js deleted file mode 100644 index 4ea7b6d..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors.js +++ /dev/null @@ -1,145 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var Objectfreeze = require("./es5.js").freeze; -var util = require("./util.js"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof OperationalError) || - e["isOperational"] === true); -} - -function isError(obj) { - return obj instanceof Error; -} - -function canAttach(obj) { - return isError(obj); -} - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - this.message = typeof message === "string" ? message : defaultMessage; - this.name = nameProperty; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -AggregateError.prototype.length = 0; -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - this.name = "OperationalError"; - this.message = message; - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - this.message = message.message; - this.stack = message.stack; - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var key = "__BluebirdErrorTypes__"; -var errorTypes = Error[key]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - notEnumerableProp(Error, key, errorTypes); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - canAttach: canAttach -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors_api_rejection.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors_api_rejection.js deleted file mode 100644 index e953e3b..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/errors_api_rejection.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var TypeError = require('./errors.js').TypeError; - -function apiRejection(msg) { - var error = new TypeError(msg); - var ret = Promise.rejected(error); - var parent = ret._peekContext(); - if (parent != null) { - parent._attachExtraTrace(error); - } - return ret; -} - -return apiRejection; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/es5.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/es5.js deleted file mode 100644 index d8f05b3..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/es5.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -var isES5 = (function(){ - "use strict"; - return this === void 0; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - keys: Object.keys, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5 - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function ObjectKeys(o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - } - - var ObjectDefineProperty = function ObjectDefineProperty(o, key, desc) { - o[key] = desc.value; - return o; - } - - var ObjectFreeze = function ObjectFreeze(obj) { - return obj; - } - - var ObjectGetPrototypeOf = function ObjectGetPrototypeOf(obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - } - - var ArrayIsArray = function ArrayIsArray(obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - } - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - defineProperty: ObjectDefineProperty, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5 - }; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/filter.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/filter.js deleted file mode 100644 index 08f67eb..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/filter.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function Promise$filter(fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function Promise$Filter(promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/finally.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/finally.js deleted file mode 100644 index 0f68296..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/finally.js +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, NEXT_FILTER, cast) { -var util = require("./util.js"); -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; -var isPrimitive = util.isPrimitive; -var thrower = util.thrower; - -function returnThis() { - return this; -} -function throwThis() { - throw this; -} -function return$(r) { - return function Promise$_returner() { - return r; - }; -} -function throw$(r) { - return function Promise$_thrower() { - throw r; - }; -} -function promisedFinally(ret, reasonOrValue, isFulfilled) { - var then; - if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { - then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); - } else { - then = isFulfilled ? returnThis : throwThis; - } - return ret._then(then, thrower, void 0, reasonOrValue, void 0); -} - -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo) - : handler(); - - if (ret !== void 0) { - var maybePromise = cast(ret, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, reasonOrValue, - promise.isFulfilled()); - } - } - - if (promise.isRejected()) { - NEXT_FILTER.e = reasonOrValue; - return NEXT_FILTER; - } else { - return reasonOrValue; - } -} - -function tapHandler(value) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo, value) - : handler(value); - - if (ret !== void 0) { - var maybePromise = cast(ret, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, value, true); - } - } - return value; -} - -Promise.prototype._passThroughHandler = -function Promise$_passThroughHandler(handler, isFinally) { - if (typeof handler !== "function") return this.then(); - - var promiseAndHandler = { - promise: this, - handler: handler - }; - - return this._then( - isFinally ? finallyHandler : tapHandler, - isFinally ? finallyHandler : void 0, void 0, - promiseAndHandler, void 0); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function Promise$finally(handler) { - return this._passThroughHandler(handler, true); -}; - -Promise.prototype.tap = function Promise$tap(handler) { - return this._passThroughHandler(handler, false); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/generators.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/generators.js deleted file mode 100644 index 58d418f..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/generators.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, apiRejection, INTERNAL, cast) { -var errors = require("./errors.js"); -var TypeError = errors.TypeError; -var deprecated = require("./util.js").deprecated; -var util = require("./util.js"); -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers) { - var _errorObj = errorObj; - var _Promise = Promise; - var len = yieldHandlers.length; - for (var i = 0; i < len; ++i) { - var result = tryCatch1(yieldHandlers[i], void 0, value); - if (result === _errorObj) { - return _Promise.reject(_errorObj.e); - } - var maybePromise = cast(result, promiseFromYieldHandler); - if (maybePromise instanceof _Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler) { - var promise = this._promise = new Promise(INTERNAL); - promise._setTrace(void 0); - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = void 0; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; -} - -PromiseSpawn.prototype.promise = function PromiseSpawn$promise() { - return this._promise; -}; - -PromiseSpawn.prototype._run = function PromiseSpawn$_run() { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = void 0; - this._next(void 0); -}; - -PromiseSpawn.prototype._continue = function PromiseSpawn$_continue(result) { - if (result === errorObj) { - this._generator = void 0; - var trace = errors.canAttach(result.e) - ? result.e : new Error(result.e + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(result.e, trace); - return; - } - - var value = result.value; - if (result.done === true) { - this._generator = void 0; - if (!this._promise._tryFollow(value)) { - this._promise._fulfill(value); - } - } else { - var maybePromise = cast(value, void 0); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, this._yieldHandlers); - if (maybePromise === null) { - this._throw(new TypeError("A value was yielded that could not be treated as a promise")); - return; - } - } - maybePromise._then( - this._next, - this._throw, - void 0, - this, - null - ); - } -}; - -PromiseSpawn.prototype._throw = function PromiseSpawn$_throw(reason) { - if (errors.canAttach(reason)) - this._promise._attachExtraTrace(reason); - this._continue( - tryCatch1(this._generator["throw"], this._generator, reason) - ); -}; - -PromiseSpawn.prototype._next = function PromiseSpawn$_next(value) { - this._continue( - tryCatch1(this._generator.next, this._generator, value) - ); -}; - -Promise.coroutine = -function Promise$Coroutine(generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(void 0, void 0, yieldHandler); - spawn._generator = generator; - spawn._next(void 0); - return spawn.promise(); - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function"); - yieldHandlers.push(fn); -}; - -Promise.spawn = function Promise$Spawn(generatorFunction) { - deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead."); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/join.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/join.js deleted file mode 100644 index 123e66b..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/join.js +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, cast, INTERNAL) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - - -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var caller = function(count) { - var values = []; - for (var i = 1; i <= count; ++i) values.push("holder.p" + i); - return new Function("holder", " \n\ - 'use strict'; \n\ - var callback = holder.fn; \n\ - return callback(values); \n\ - ".replace(/values/g, values.join(", "))); - }; - var thenCallbacks = []; - var callers = [void 0]; - for (var i = 1; i <= 5; ++i) { - thenCallbacks.push(thenCallback(i)); - callers.push(caller(i)); - } - - var Holder = function(total, fn) { - this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; - this.fn = fn; - this.total = total; - this.now = 0; - }; - - Holder.prototype.callers = callers; - Holder.prototype.checkFulfillment = function(promise) { - var now = this.now; - now++; - var total = this.total; - if (now >= total) { - var handler = this.callers[total]; - var ret = tryCatch1(handler, void 0, this); - if (ret === errorObj) { - promise._rejectUnchecked(ret.e); - } else if (!promise._tryFollow(ret)) { - promise._fulfillUnchecked(ret); - } - } else { - this.now = now; - } - }; -} - - - - -Promise.join = function Promise$Join() { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (last < 6 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - var holder = new Holder(last, fn); - var reject = ret._reject; - var callbacks = thenCallbacks; - for (var i = 0; i < last; ++i) { - var maybePromise = cast(arguments[i], void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._then(callbacks[i], reject, - void 0, ret, holder); - } else if (maybePromise.isFulfilled()) { - callbacks[i].call(ret, - maybePromise._settledValue, holder); - } else { - ret._reject(maybePromise._settledValue); - maybePromise._unsetRejectionIsUnhandled(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - return ret; - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - var ret = new PromiseArray(args).promise(); - return fn !== void 0 ? ret.spread(fn) : ret; -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/nodeify.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/nodeify.js deleted file mode 100644 index e5658d6..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/nodeify.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -var util = require("./util.js"); -var async = require("./async.js"); -var tryCatch2 = util.tryCatch2; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -function thrower(r) { - throw r; -} - -function Promise$_spreadAdapter(val, receiver) { - if (!util.isArray(val)) return Promise$_successAdapter(val, receiver); - var ret = util.tryCatchApply(this, [null].concat(val), receiver); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} - -function Promise$_successAdapter(val, receiver) { - var nodeback = this; - var ret = val === void 0 - ? tryCatch1(nodeback, receiver, null) - : tryCatch2(nodeback, receiver, null, val); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} -function Promise$_errorAdapter(reason, receiver) { - var nodeback = this; - var ret = tryCatch1(nodeback, receiver, reason); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } -} - -Promise.prototype.nodeify = function Promise$nodeify(nodeback, options) { - if (typeof nodeback == "function") { - var adapter = Promise$_successAdapter; - if (options !== void 0 && Object(options).spread) { - adapter = Promise$_spreadAdapter; - } - this._then( - adapter, - Promise$_errorAdapter, - void 0, - nodeback, - this._boundTo - ); - } - return this; -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/progress.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/progress.js deleted file mode 100644 index 960d053..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/progress.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -Promise.prototype.progressed = function Promise$progressed(handler) { - return this._then(void 0, void 0, handler, void 0, void 0); -}; - -Promise.prototype._progress = function Promise$_progress(progressValue) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._progressUnchecked(progressValue); - -}; - -Promise.prototype._clearFirstHandlerData$Base = -Promise.prototype._clearFirstHandlerData; -Promise.prototype._clearFirstHandlerData = -function Promise$_clearFirstHandlerData() { - this._clearFirstHandlerData$Base(); - this._progressHandler0 = void 0; -}; - -Promise.prototype._progressHandlerAt = -function Promise$_progressHandlerAt(index) { - return index === 0 - ? this._progressHandler0 - : this[(index << 2) + index - 5 + 2]; -}; - -Promise.prototype._doProgressWith = -function Promise$_doProgressWith(progression) { - var progressValue = progression.value; - var handler = progression.handler; - var promise = progression.promise; - var receiver = progression.receiver; - - var ret = tryCatch1(handler, receiver, progressValue); - if (ret === errorObj) { - if (ret.e != null && - ret.e.name !== "StopProgressPropagation") { - var trace = errors.canAttach(ret.e) - ? ret.e : new Error(ret.e + ""); - promise._attachExtraTrace(trace); - promise._progress(ret.e); - } - } else if (ret instanceof Promise) { - ret._then(promise._progress, null, null, promise, void 0); - } else { - promise._progress(ret); - } -}; - - -Promise.prototype._progressUnchecked = -function Promise$_progressUnchecked(progressValue) { - if (!this.isPending()) return; - var len = this._length(); - var progress = this._progress; - for (var i = 0; i < len; i++) { - var handler = this._progressHandlerAt(i); - var promise = this._promiseAt(i); - if (!(promise instanceof Promise)) { - var receiver = this._receiverAt(i); - if (typeof handler === "function") { - handler.call(receiver, progressValue, promise); - } else if (receiver instanceof Promise && receiver._isProxied()) { - receiver._progressUnchecked(progressValue); - } else if (receiver instanceof PromiseArray) { - receiver._promiseProgressed(progressValue, promise); - } - continue; - } - - if (typeof handler === "function") { - this._doProgressWith(({handler: handler, -promise: promise, -receiver: this._receiverAt(i), -value: progressValue})); - } else { - progress.call(promise, progressValue); - } - } -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise.js deleted file mode 100644 index f585759..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise.js +++ /dev/null @@ -1,1077 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict(bluebird) { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -module.exports = function() { -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); - -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {e: null}; - -var cast = require("./thenables.js")(Promise, INTERNAL); -var PromiseArray = require("./promise_array.js")(Promise, INTERNAL, cast); -var CapturedTrace = require("./captured_trace.js")(); -var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); -var PromiseResolver = require("./promise_resolver.js"); - -var isArray = util.isArray; - -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var tryCatch2 = util.tryCatch2; -var tryCatchApply = util.tryCatchApply; -var RangeError = errors.RangeError; -var TypeError = errors.TypeError; -var CancellationError = errors.CancellationError; -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var originatesFromRejection = errors.originatesFromRejection; -var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection; -var canAttach = errors.canAttach; -var thrower = util.thrower; -var apiRejection = require("./errors_api_rejection")(Promise); - - -var makeSelfResolutionError = function Promise$_makeSelfResolutionError() { - return new TypeError("circular promise resolution chain"); -}; - -function Promise(resolver) { - if (typeof resolver !== "function") { - throw new TypeError("the promise constructor requires a resolver function"); - } - if (this.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly"); - } - this._bitField = 0; - this._fulfillmentHandler0 = void 0; - this._rejectionHandler0 = void 0; - this._promise0 = void 0; - this._receiver0 = void 0; - this._settledValue = void 0; - this._boundTo = void 0; - if (resolver !== INTERNAL) this._resolveFromResolver(resolver); -} - -function returnFirstElement(elements) { - return elements[0]; -} - -Promise.prototype.bind = function Promise$bind(thisArg) { - var maybePromise = cast(thisArg, void 0); - var ret = new Promise(INTERNAL); - if (maybePromise instanceof Promise) { - var binder = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - var p = Promise.all([this, binder]).then(returnFirstElement); - ret._follow(p); - } else { - ret._follow(this); - ret._setBoundTo(thisArg); - } - ret._propagateFrom(this, 2 | 1); - return ret; -}; - -Promise.prototype.toString = function Promise$toString() { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = -function Promise$catch(fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (typeof item === "function") { - catchInstances[j++] = item; - } else { - var catchFilterTypeError = - new TypeError( - "A catch filter must be an error constructor " - + "or a filter function"); - - this._attachExtraTrace(catchFilterTypeError); - this._reject(catchFilterTypeError); - return; - } - } - catchInstances.length = j; - fn = arguments[i]; - - this._resetTrace(); - var catchFilter = new CatchFilter(catchInstances, fn, this); - return this._then(void 0, catchFilter.doFilter, void 0, - catchFilter, void 0); - } - return this._then(void 0, fn, void 0, void 0, void 0); -}; - -Promise.prototype.then = -function Promise$then(didFulfill, didReject, didProgress) { - return this._then(didFulfill, didReject, didProgress, - void 0, void 0); -}; - - -Promise.prototype.done = -function Promise$done(didFulfill, didReject, didProgress) { - var promise = this._then(didFulfill, didReject, didProgress, - void 0, void 0); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function Promise$spread(didFulfill, didReject) { - return this._then(didFulfill, didReject, void 0, - APPLY, void 0); -}; - -Promise.prototype.isCancellable = function Promise$isCancellable() { - return !this.isResolved() && - this._cancellable(); -}; - -Promise.prototype.toJSON = function Promise$toJSON() { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: void 0, - rejectionReason: void 0 - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this._settledValue; - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this._settledValue; - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function Promise$all() { - return new PromiseArray(this).promise(); -}; - - -Promise.is = function Promise$Is(val) { - return val instanceof Promise; -}; - -Promise.all = function Promise$All(promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.prototype.error = function Promise$_error(fn) { - return this.caught(originatesFromRejection, fn); -}; - -Promise.prototype._resolveFromSyncValue = -function Promise$_resolveFromSyncValue(value) { - if (value === errorObj) { - this._cleanValues(); - this._setRejected(); - this._settledValue = value.e; - this._ensurePossibleRejectionHandled(); - } else { - var maybePromise = cast(value, void 0); - if (maybePromise instanceof Promise) { - this._follow(maybePromise); - } else { - this._cleanValues(); - this._setFulfilled(); - this._settledValue = value; - } - } -}; - -Promise.method = function Promise$_Method(fn) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); - } - return function Promise$_method() { - var value; - switch(arguments.length) { - case 0: value = tryCatch1(fn, this, void 0); break; - case 1: value = tryCatch1(fn, this, arguments[0]); break; - case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break; - default: - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - value = tryCatchApply(fn, args, this); break; - } - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) { - if (typeof fn !== "function") { - return apiRejection("fn must be a function"); - } - var value = isArray(args) - ? tryCatchApply(fn, args, ctx) - : tryCatch1(fn, ctx, args); - - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.defer = Promise.pending = function Promise$Defer() { - var promise = new Promise(INTERNAL); - promise._setTrace(void 0); - return new PromiseResolver(promise); -}; - -Promise.bind = function Promise$Bind(thisArg) { - var maybePromise = cast(thisArg, void 0); - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - - if (maybePromise instanceof Promise) { - var p = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - ret._follow(p); - } else { - ret._setBoundTo(thisArg); - ret._setFulfilled(); - } - return ret; -}; - -Promise.cast = function Promise$_Cast(obj) { - var ret = cast(obj, void 0); - if (!(ret instanceof Promise)) { - var val = ret; - ret = new Promise(INTERNAL); - ret._setTrace(void 0); - ret._setFulfilled(); - ret._cleanValues(); - ret._settledValue = val; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function Promise$Reject(reason) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - markAsOriginatingFromRejection(reason); - ret._cleanValues(); - ret._setRejected(); - ret._settledValue = reason; - if (!canAttach(reason)) { - var trace = new Error(reason + ""); - ret._setCarriedStackTrace(trace); - } - ret._ensurePossibleRejectionHandled(); - return ret; -}; - -Promise.onPossiblyUnhandledRejection = -function Promise$OnPossiblyUnhandledRejection(fn) { - CapturedTrace.possiblyUnhandledRejection = typeof fn === "function" - ? fn : void 0; -}; - -var unhandledRejectionHandled; -Promise.onUnhandledRejectionHandled = -function Promise$onUnhandledRejectionHandled(fn) { - unhandledRejectionHandled = typeof fn === "function" ? fn : void 0; -}; - -var debugging = false || !!( - typeof process !== "undefined" && - typeof process.execPath === "string" && - typeof process.env === "object" && - (process.env["BLUEBIRD_DEBUG"] || - process.env["NODE_ENV"] === "development") -); - - -Promise.longStackTraces = function Promise$LongStackTraces() { - if (async.haveItemsQueued() && - debugging === false - ) { - throw new Error("cannot enable long stack traces after promises have been created"); - } - debugging = CapturedTrace.isSupported(); -}; - -Promise.hasLongStackTraces = function Promise$HasLongStackTraces() { - return debugging && CapturedTrace.isSupported(); -}; - -Promise.prototype._then = -function Promise$_then( - didFulfill, - didReject, - didProgress, - receiver, - internalData -) { - var haveInternalData = internalData !== void 0; - var ret = haveInternalData ? internalData : new Promise(INTERNAL); - - if (!haveInternalData) { - if (debugging) { - var haveSameContext = this._peekContext() === this._traceParent; - ret._traceParent = haveSameContext ? this._traceParent : this; - } - ret._propagateFrom(this, 7); - } - - var callbackIndex = - this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - - if (this.isResolved()) { - this._queueSettleAt(callbackIndex); - } - - return ret; -}; - -Promise.prototype._length = function Promise$_length() { - return this._bitField & 262143; -}; - -Promise.prototype._isFollowingOrFulfilledOrRejected = -function Promise$_isFollowingOrFulfilledOrRejected() { - return (this._bitField & 939524096) > 0; -}; - -Promise.prototype._isFollowing = function Promise$_isFollowing() { - return (this._bitField & 536870912) === 536870912; -}; - -Promise.prototype._setLength = function Promise$_setLength(len) { - this._bitField = (this._bitField & -262144) | - (len & 262143); -}; - -Promise.prototype._setFulfilled = function Promise$_setFulfilled() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._setRejected = function Promise$_setRejected() { - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._setFollowing = function Promise$_setFollowing() { - this._bitField = this._bitField | 536870912; -}; - -Promise.prototype._setIsFinal = function Promise$_setIsFinal() { - this._bitField = this._bitField | 33554432; -}; - -Promise.prototype._isFinal = function Promise$_isFinal() { - return (this._bitField & 33554432) > 0; -}; - -Promise.prototype._cancellable = function Promise$_cancellable() { - return (this._bitField & 67108864) > 0; -}; - -Promise.prototype._setCancellable = function Promise$_setCancellable() { - this._bitField = this._bitField | 67108864; -}; - -Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() { - this._bitField = this._bitField & (~67108864); -}; - -Promise.prototype._setRejectionIsUnhandled = -function Promise$_setRejectionIsUnhandled() { - this._bitField = this._bitField | 2097152; -}; - -Promise.prototype._unsetRejectionIsUnhandled = -function Promise$_unsetRejectionIsUnhandled() { - this._bitField = this._bitField & (~2097152); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = -function Promise$_isRejectionUnhandled() { - return (this._bitField & 2097152) > 0; -}; - -Promise.prototype._setUnhandledRejectionIsNotified = -function Promise$_setUnhandledRejectionIsNotified() { - this._bitField = this._bitField | 524288; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = -function Promise$_unsetUnhandledRejectionIsNotified() { - this._bitField = this._bitField & (~524288); -}; - -Promise.prototype._isUnhandledRejectionNotified = -function Promise$_isUnhandledRejectionNotified() { - return (this._bitField & 524288) > 0; -}; - -Promise.prototype._setCarriedStackTrace = -function Promise$_setCarriedStackTrace(capturedTrace) { - this._bitField = this._bitField | 1048576; - this._fulfillmentHandler0 = capturedTrace; -}; - -Promise.prototype._unsetCarriedStackTrace = -function Promise$_unsetCarriedStackTrace() { - this._bitField = this._bitField & (~1048576); - this._fulfillmentHandler0 = void 0; -}; - -Promise.prototype._isCarryingStackTrace = -function Promise$_isCarryingStackTrace() { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._getCarriedStackTrace = -function Promise$_getCarriedStackTrace() { - return this._isCarryingStackTrace() - ? this._fulfillmentHandler0 - : void 0; -}; - -Promise.prototype._receiverAt = function Promise$_receiverAt(index) { - var ret = index === 0 - ? this._receiver0 - : this[(index << 2) + index - 5 + 4]; - if (this._isBound() && ret === void 0) { - return this._boundTo; - } - return ret; -}; - -Promise.prototype._promiseAt = function Promise$_promiseAt(index) { - return index === 0 - ? this._promise0 - : this[(index << 2) + index - 5 + 3]; -}; - -Promise.prototype._fulfillmentHandlerAt = -function Promise$_fulfillmentHandlerAt(index) { - return index === 0 - ? this._fulfillmentHandler0 - : this[(index << 2) + index - 5 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = -function Promise$_rejectionHandlerAt(index) { - return index === 0 - ? this._rejectionHandler0 - : this[(index << 2) + index - 5 + 1]; -}; - -Promise.prototype._addCallbacks = function Promise$_addCallbacks( - fulfill, - reject, - progress, - promise, - receiver -) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - if (receiver !== void 0) this._receiver0 = receiver; - if (typeof fulfill === "function" && !this._isCarryingStackTrace()) - this._fulfillmentHandler0 = fulfill; - if (typeof reject === "function") this._rejectionHandler0 = reject; - if (typeof progress === "function") this._progressHandler0 = progress; - } else { - var base = (index << 2) + index - 5; - this[base + 3] = promise; - this[base + 4] = receiver; - this[base + 0] = typeof fulfill === "function" - ? fulfill : void 0; - this[base + 1] = typeof reject === "function" - ? reject : void 0; - this[base + 2] = typeof progress === "function" - ? progress : void 0; - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._setProxyHandlers = -function Promise$_setProxyHandlers(receiver, promiseSlotValue) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - if (index === 0) { - this._promise0 = promiseSlotValue; - this._receiver0 = receiver; - } else { - var base = (index << 2) + index - 5; - this[base + 3] = promiseSlotValue; - this[base + 4] = receiver; - this[base + 0] = - this[base + 1] = - this[base + 2] = void 0; - } - this._setLength(index + 1); -}; - -Promise.prototype._proxyPromiseArray = -function Promise$_proxyPromiseArray(promiseArray, index) { - this._setProxyHandlers(promiseArray, index); -}; - -Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) { - promise._setProxied(); - this._setProxyHandlers(promise, -15); -}; - -Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) { - if (obj !== void 0) { - this._bitField = this._bitField | 8388608; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~8388608); - } -}; - -Promise.prototype._isBound = function Promise$_isBound() { - return (this._bitField & 8388608) === 8388608; -}; - -Promise.prototype._resolveFromResolver = -function Promise$_resolveFromResolver(resolver) { - var promise = this; - this._setTrace(void 0); - this._pushContext(); - - function Promise$_resolver(val) { - if (promise._tryFollow(val)) { - return; - } - promise._fulfill(val); - } - function Promise$_rejecter(val) { - var trace = canAttach(val) ? val : new Error(val + ""); - promise._attachExtraTrace(trace); - markAsOriginatingFromRejection(val); - promise._reject(val, trace === val ? void 0 : trace); - } - var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter); - this._popContext(); - - if (r !== void 0 && r === errorObj) { - var e = r.e; - var trace = canAttach(e) ? e : new Error(e + ""); - promise._reject(e, trace); - } -}; - -Promise.prototype._spreadSlowCase = -function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) { - var promiseForAll = new PromiseArray(values).promise(); - var promise2 = promiseForAll._then(function() { - return targetFn.apply(boundTo, arguments); - }, void 0, void 0, APPLY, void 0); - promise._follow(promise2); -}; - -Promise.prototype._callSpread = -function Promise$_callSpread(handler, promise, value) { - var boundTo = this._boundTo; - if (isArray(value)) { - for (var i = 0, len = value.length; i < len; ++i) { - if (cast(value[i], void 0) instanceof Promise) { - this._spreadSlowCase(handler, promise, value, boundTo); - return; - } - } - } - promise._pushContext(); - return tryCatchApply(handler, value, boundTo); -}; - -Promise.prototype._callHandler = -function Promise$_callHandler( - handler, receiver, promise, value) { - var x; - if (receiver === APPLY && !this.isRejected()) { - x = this._callSpread(handler, promise, value); - } else { - promise._pushContext(); - x = tryCatch1(handler, receiver, value); - } - promise._popContext(); - return x; -}; - -Promise.prototype._settlePromiseFromHandler = -function Promise$_settlePromiseFromHandler( - handler, receiver, value, promise -) { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - return; - } - var x = this._callHandler(handler, receiver, promise, value); - if (promise._isFollowing()) return; - - if (x === errorObj || x === promise || x === NEXT_FILTER) { - var err = x === promise - ? makeSelfResolutionError() - : x.e; - var trace = canAttach(err) ? err : new Error(err + ""); - if (x !== NEXT_FILTER) promise._attachExtraTrace(trace); - promise._rejectUnchecked(err, trace); - } else { - var castValue = cast(x, promise); - if (castValue instanceof Promise) { - if (castValue.isRejected() && - !castValue._isCarryingStackTrace() && - !canAttach(castValue._settledValue)) { - var trace = new Error(castValue._settledValue + ""); - promise._attachExtraTrace(trace); - castValue._setCarriedStackTrace(trace); - } - promise._follow(castValue); - promise._propagateFrom(castValue, 1); - } else { - promise._fulfillUnchecked(x); - } - } -}; - -Promise.prototype._follow = -function Promise$_follow(promise) { - this._setFollowing(); - - if (promise.isPending()) { - this._propagateFrom(promise, 1); - promise._proxyPromise(this); - } else if (promise.isFulfilled()) { - this._fulfillUnchecked(promise._settledValue); - } else { - this._rejectUnchecked(promise._settledValue, - promise._getCarriedStackTrace()); - } - - if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled(); - - if (debugging && - promise._traceParent == null) { - promise._traceParent = this; - } -}; - -Promise.prototype._tryFollow = -function Promise$_tryFollow(value) { - if (this._isFollowingOrFulfilledOrRejected() || - value === this) { - return false; - } - var maybePromise = cast(value, void 0); - if (!(maybePromise instanceof Promise)) { - return false; - } - this._follow(maybePromise); - return true; -}; - -Promise.prototype._resetTrace = function Promise$_resetTrace() { - if (debugging) { - this._trace = new CapturedTrace(this._peekContext() === void 0); - } -}; - -Promise.prototype._setTrace = function Promise$_setTrace(parent) { - if (debugging) { - var context = this._peekContext(); - this._traceParent = context; - var isTopLevel = context === void 0; - if (parent !== void 0 && - parent._traceParent === context) { - this._trace = parent._trace; - } else { - this._trace = new CapturedTrace(isTopLevel); - } - } - return this; -}; - -Promise.prototype._attachExtraTrace = -function Promise$_attachExtraTrace(error) { - if (debugging) { - var promise = this; - var stack = error.stack; - stack = typeof stack === "string" ? stack.split("\n") : []; - CapturedTrace.protectErrorMessageNewlines(stack); - var headerLineCount = 1; - var combinedTraces = 1; - while(promise != null && - promise._trace != null) { - stack = CapturedTrace.combine( - stack, - promise._trace.stack.split("\n") - ); - promise = promise._traceParent; - combinedTraces++; - } - - var stackTraceLimit = Error.stackTraceLimit || 10; - var max = (stackTraceLimit + headerLineCount) * combinedTraces; - var len = stack.length; - if (len > max) { - stack.length = max; - } - - if (len > 0) - stack[0] = stack[0].split("\u0002\u0000\u0001").join("\n"); - - if (stack.length <= headerLineCount) { - error.stack = "(No stack trace)"; - } else { - error.stack = stack.join("\n"); - } - } -}; - -Promise.prototype._cleanValues = function Promise$_cleanValues() { - if (this._cancellable()) { - this._cancellationParent = void 0; - } -}; - -Promise.prototype._propagateFrom = -function Promise$_propagateFrom(parent, flags) { - if ((flags & 1) > 0 && parent._cancellable()) { - this._setCancellable(); - this._cancellationParent = parent; - } - if ((flags & 4) > 0) { - this._setBoundTo(parent._boundTo); - } - if ((flags & 2) > 0) { - this._setTrace(parent); - } -}; - -Promise.prototype._fulfill = function Promise$_fulfill(value) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._fulfillUnchecked(value); -}; - -Promise.prototype._reject = -function Promise$_reject(reason, carriedStackTrace) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._rejectUnchecked(reason, carriedStackTrace); -}; - -Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) { - var handler = this.isFulfilled() - ? this._fulfillmentHandlerAt(index) - : this._rejectionHandlerAt(index); - - var value = this._settledValue; - var receiver = this._receiverAt(index); - var promise = this._promiseAt(index); - - if (typeof handler === "function") { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } else { - var done = false; - var isFulfilled = this.isFulfilled(); - if (receiver !== void 0) { - if (receiver instanceof Promise && - receiver._isProxied()) { - receiver._unsetProxied(); - - if (isFulfilled) receiver._fulfillUnchecked(value); - else receiver._rejectUnchecked(value, - this._getCarriedStackTrace()); - done = true; - } else if (receiver instanceof PromiseArray) { - if (isFulfilled) receiver._promiseFulfilled(value, promise); - else receiver._promiseRejected(value, promise); - done = true; - } - } - - if (!done) { - if (isFulfilled) promise._fulfill(value); - else promise._reject(value, this._getCarriedStackTrace()); - } - } - - if (index >= 4) { - this._queueGC(); - } -}; - -Promise.prototype._isProxied = function Promise$_isProxied() { - return (this._bitField & 4194304) === 4194304; -}; - -Promise.prototype._setProxied = function Promise$_setProxied() { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._unsetProxied = function Promise$_unsetProxied() { - this._bitField = this._bitField & (~4194304); -}; - -Promise.prototype._isGcQueued = function Promise$_isGcQueued() { - return (this._bitField & -1073741824) === -1073741824; -}; - -Promise.prototype._setGcQueued = function Promise$_setGcQueued() { - this._bitField = this._bitField | -1073741824; -}; - -Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() { - this._bitField = this._bitField & (~-1073741824); -}; - -Promise.prototype._queueGC = function Promise$_queueGC() { - if (this._isGcQueued()) return; - this._setGcQueued(); - async.invokeLater(this._gc, this, void 0); -}; - -Promise.prototype._gc = function Promise$gc() { - var len = this._length() * 5 - 5; - for (var i = 0; i < len; i++) { - delete this[i]; - } - this._clearFirstHandlerData(); - this._setLength(0); - this._unsetGcQueued(); -}; - -Promise.prototype._clearFirstHandlerData = -function Promise$_clearFirstHandlerData() { - this._fulfillmentHandler0 = void 0; - this._rejectionHandler0 = void 0; - this._promise0 = void 0; - this._receiver0 = void 0; -}; - -Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) { - if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); - this._settlePromiseAt(index); -}; - -Promise.prototype._fulfillUnchecked = -function Promise$_fulfillUnchecked(value) { - if (!this.isPending()) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err, void 0); - } - this._cleanValues(); - this._setFulfilled(); - this._settledValue = value; - var len = this._length(); - - if (len > 0) { - this._settlePromises(len); - } -}; - -Promise.prototype._rejectUncheckedCheckError = -function Promise$_rejectUncheckedCheckError(reason) { - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._rejectUnchecked(reason, trace === reason ? void 0 : trace); -}; - -Promise.prototype._rejectUnchecked = -function Promise$_rejectUnchecked(reason, trace) { - if (!this.isPending()) return; - if (reason === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err); - } - this._cleanValues(); - this._setRejected(); - this._settledValue = reason; - - if (this._isFinal()) { - async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace); - return; - } - var len = this._length(); - - if (trace !== void 0) this._setCarriedStackTrace(trace); - - if (len > 0) { - this._rejectPromises(null); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._rejectPromises = function Promise$_rejectPromises() { - this._settlePromises(); - this._unsetCarriedStackTrace(); -}; - -Promise.prototype._settlePromises = function Promise$_settlePromises() { - var len = this._length(); - for (var i = 0; i < len; i++) { - this._settlePromiseAt(i); - } -}; - -Promise.prototype._ensurePossibleRejectionHandled = -function Promise$_ensurePossibleRejectionHandled() { - this._setRejectionIsUnhandled(); - if (CapturedTrace.possiblyUnhandledRejection !== void 0) { - async.invokeLater(this._notifyUnhandledRejection, this, void 0); - } -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = -function Promise$_notifyUnhandledRejectionIsHandled() { - if (typeof unhandledRejectionHandled === "function") { - async.invokeLater(unhandledRejectionHandled, void 0, this); - } -}; - -Promise.prototype._notifyUnhandledRejection = -function Promise$_notifyUnhandledRejection() { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue; - var trace = this._getCarriedStackTrace(); - - this._setUnhandledRejectionIsNotified(); - - if (trace !== void 0) { - this._unsetCarriedStackTrace(); - reason = trace; - } - if (typeof CapturedTrace.possiblyUnhandledRejection === "function") { - CapturedTrace.possiblyUnhandledRejection(reason, this); - } - } -}; - -var contextStack = []; -Promise.prototype._peekContext = function Promise$_peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return void 0; - -}; - -Promise.prototype._pushContext = function Promise$_pushContext() { - if (!debugging) return; - contextStack.push(this); -}; - -Promise.prototype._popContext = function Promise$_popContext() { - if (!debugging) return; - contextStack.pop(); -}; - -Promise.noConflict = function Promise$NoConflict() { - return noConflict(Promise); -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function"); - async._schedule = fn; -}; - -if (!CapturedTrace.isSupported()) { - Promise.longStackTraces = function(){}; - debugging = false; -} - -Promise._makeSelfResolutionError = makeSelfResolutionError; -require("./finally.js")(Promise, NEXT_FILTER, cast); -require("./direct_resolve.js")(Promise); -require("./synchronous_inspection.js")(Promise); -require("./join.js")(Promise, PromiseArray, cast, INTERNAL); -Promise.RangeError = RangeError; -Promise.CancellationError = CancellationError; -Promise.TimeoutError = TimeoutError; -Promise.TypeError = TypeError; -Promise.OperationalError = OperationalError; -Promise.RejectionError = OperationalError; -Promise.AggregateError = errors.AggregateError; - -util.toFastProperties(Promise); -util.toFastProperties(Promise.prototype); -Promise.Promise = Promise; -require('./timers.js')(Promise,INTERNAL,cast); -require('./race.js')(Promise,INTERNAL,cast); -require('./call_get.js')(Promise); -require('./generators.js')(Promise,apiRejection,INTERNAL,cast); -require('./map.js')(Promise,PromiseArray,apiRejection,cast,INTERNAL); -require('./nodeify.js')(Promise); -require('./promisify.js')(Promise,INTERNAL); -require('./props.js')(Promise,PromiseArray,cast); -require('./reduce.js')(Promise,PromiseArray,apiRejection,cast,INTERNAL); -require('./settle.js')(Promise,PromiseArray); -require('./some.js')(Promise,PromiseArray,apiRejection); -require('./progress.js')(Promise,PromiseArray); -require('./cancel.js')(Promise,INTERNAL); -require('./filter.js')(Promise,INTERNAL); -require('./any.js')(Promise,PromiseArray); -require('./each.js')(Promise,INTERNAL); -require('./using.js')(Promise,apiRejection,cast); - -Promise.prototype = Promise.prototype; -return Promise; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_array.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_array.js deleted file mode 100644 index db85c8a..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_array.js +++ /dev/null @@ -1,202 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, cast) { -var canAttach = require("./errors.js").canAttach; -var util = require("./util.js"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -1: return void 0; - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - var parent = void 0; - if (values instanceof Promise) { - parent = values; - promise._propagateFrom(parent, 1 | 4); - } - promise._setTrace(parent); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(void 0, -2); -} -PromiseArray.prototype.length = function PromiseArray$length() { - return this._length; -}; - -PromiseArray.prototype.promise = function PromiseArray$promise() { - return this._promise; -}; - -PromiseArray.prototype._init = -function PromiseArray$_init(_, resolveValueIfEmpty) { - var values = cast(this._values, void 0); - if (values instanceof Promise) { - this._values = values; - values._setBoundTo(this._promise._boundTo); - if (values.isFulfilled()) { - values = values._settledValue; - if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable"); - this.__hardReject__(err); - return; - } - } else if (values.isPending()) { - values._then( - PromiseArray$_init, - this._reject, - void 0, - this, - resolveValueIfEmpty - ); - return; - } else { - values._unsetRejectionIsUnhandled(); - this._reject(values._settledValue); - return; - } - } else if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable"); - this.__hardReject__(err); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - var len = this.getActualLength(values.length); - var newLen = len; - var newValues = this.shouldCopyValues() ? new Array(len) : this._values; - var isDirectScanNeeded = false; - for (var i = 0; i < len; ++i) { - var maybePromise = cast(values[i], void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, i); - } else { - maybePromise._unsetRejectionIsUnhandled(); - isDirectScanNeeded = true; - } - } else { - isDirectScanNeeded = true; - } - newValues[i] = maybePromise; - } - this._values = newValues; - this._length = newLen; - if (isDirectScanNeeded) { - this._scanDirectValues(len); - } -}; - -PromiseArray.prototype._settlePromiseAt = -function PromiseArray$_settlePromiseAt(index) { - var value = this._values[index]; - if (!(value instanceof Promise)) { - this._promiseFulfilled(value, index); - } else if (value.isFulfilled()) { - this._promiseFulfilled(value._settledValue, index); - } else if (value.isRejected()) { - this._promiseRejected(value._settledValue, index); - } -}; - -PromiseArray.prototype._scanDirectValues = -function PromiseArray$_scanDirectValues(len) { - for (var i = 0; i < len; ++i) { - if (this._isResolved()) { - break; - } - this._settlePromiseAt(i); - } -}; - -PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype.__hardReject__ = -PromiseArray.prototype._reject = function PromiseArray$_reject(reason) { - this._values = null; - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(reason, trace); -}; - -PromiseArray.prototype._promiseProgressed = -function PromiseArray$_promiseProgressed(progressValue, index) { - if (this._isResolved()) return; - this._promise._progress({ - index: index, - value: progressValue - }); -}; - - -PromiseArray.prototype._promiseFulfilled = -function PromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -PromiseArray.prototype._promiseRejected = -function PromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; - this._totalResolved++; - this._reject(reason); -}; - -PromiseArray.prototype.shouldCopyValues = -function PromiseArray$_shouldCopyValues() { - return true; -}; - -PromiseArray.prototype.getActualLength = -function PromiseArray$getActualLength(len) { - return len; -}; - -return PromiseArray; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_resolver.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_resolver.js deleted file mode 100644 index afd14bf..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promise_resolver.js +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var util = require("./util.js"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors.js"); -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var async = require("./async.js"); -var haveGetters = util.haveGetters; -var es5 = require("./es5.js"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - } else { - ret = obj; - } - errors.markAsOriginatingFromRejection(ret); - return ret; -} - -function nodebackForPromise(promise) { - function PromiseResolver$_callback(err, value) { - if (promise === null) return; - - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (arguments.length > 2) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - promise._fulfill(args); - } else { - promise._fulfill(value); - } - - promise = null; - } - return PromiseResolver$_callback; -} - - -var PromiseResolver; -if (!haveGetters) { - PromiseResolver = function PromiseResolver(promise) { - this.promise = promise; - this.asCallback = nodebackForPromise(promise); - this.callback = this.asCallback; - }; -} -else { - PromiseResolver = function PromiseResolver(promise) { - this.promise = promise; - }; -} -if (haveGetters) { - var prop = { - get: function() { - return nodebackForPromise(this.promise); - } - }; - es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); - es5.defineProperty(PromiseResolver.prototype, "callback", prop); -} - -PromiseResolver._nodebackForPromise = nodebackForPromise; - -PromiseResolver.prototype.toString = function PromiseResolver$toString() { - return "[object PromiseResolver]"; -}; - -PromiseResolver.prototype.resolve = -PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - - var promise = this.promise; - if (promise._tryFollow(value)) { - return; - } - promise._fulfill(value); -}; - -PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - - var promise = this.promise; - errors.markAsOriginatingFromRejection(reason); - var trace = errors.canAttach(reason) ? reason : new Error(reason + ""); - promise._attachExtraTrace(trace); - promise._reject(reason); - if (trace !== reason) { - this._setCarriedStackTrace(trace); - } -}; - -PromiseResolver.prototype.progress = -function PromiseResolver$progress(value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead."); - } - this.promise._progress(value); -}; - -PromiseResolver.prototype.cancel = function PromiseResolver$cancel() { - this.promise.cancel((void 0)); -}; - -PromiseResolver.prototype.timeout = function PromiseResolver$timeout() { - this.reject(new TimeoutError("timeout")); -}; - -PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() { - return this.promise.isResolved(); -}; - -PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() { - return this.promise.toJSON(); -}; - -PromiseResolver.prototype._setCarriedStackTrace = -function PromiseResolver$_setCarriedStackTrace(trace) { - if (this.promise.isRejected()) { - this.promise._setCarriedStackTrace(trace); - } -}; - -module.exports = PromiseResolver; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promisify.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promisify.js deleted file mode 100644 index 933e0cf..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/promisify.js +++ /dev/null @@ -1,326 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = require("./util.js"); -var nodebackForPromise = require("./promise_resolver.js") - ._nodebackForPromise; -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = require("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultFilter = function(name, func) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - !util.isClass(func); -}; -var defaultPromisified = {__isPromisified__: true}; - - -function escapeIdentRegex(str) { - return str.replace(/([$])/, "\\$"); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API " + - "that has normal methods with '"+suffix+"'-suffix"); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -function switchCaseArgumentOrder(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 5); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - if (i === likelyArgumentCount) continue; - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 5; ++i) { - ret.push(i); - } - return ret; -} - -function argumentSequence(argumentCount) { - return util.filledRange(argumentCount, "arguments[", "]"); -} - -function parameterDeclaration(parameterCount) { - return util.filledRange(parameterCount, "_arg", ""); -} - -function parameterCount(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -} - -function generatePropertyAccess(key) { - if (util.isIdentifier(key)) { - return "." + key; - } - else return "['" + key.replace(/(['\\])/g, "\\$1") + "']"; -} - -function makeNodePromisifiedEval(callback, receiver, originalName, fn, suffix) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var callbackName = - (typeof originalName === "string" && util.isIdentifier(originalName) - ? originalName + suffix - : "promisified"); - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (typeof callback === "string") { - ret = " \n\ - this.method(args, fn); \n\ - break; \n\ - ".replace(".method", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - ret = " \n\ - callback.call(this, args, fn); \n\ - break; \n\ - "; - } else if (receiver !== void 0) { - ret = " \n\ - callback.call(receiver, args, fn); \n\ - break; \n\ - "; - } else { - ret = " \n\ - callback(args, fn); \n\ - break; \n\ - "; - } - return ret.replace("args", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for(var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - var codeForCall; - if (typeof callback === "string") { - codeForCall = " \n\ - this.property.apply(this, args); \n\ - " - .replace(".property", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - codeForCall = " \n\ - callback.apply(this, args); \n\ - "; - } else { - codeForCall = " \n\ - callback.apply(receiver, args); \n\ - "; - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = fn; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", codeForCall); - return ret; - } - - return new Function("Promise", - "callback", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "INTERNAL"," \n\ - var ret = function FunctionName(Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._setTrace(void 0); \n\ - var fn = nodebackForPromise(promise); \n\ - try { \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - } catch (e) { \n\ - var wrapped = maybeWrapAsError(e); \n\ - promise._attachExtraTrace(wrapped); \n\ - promise._reject(wrapped); \n\ - } \n\ - return promise; \n\ - }; \n\ - ret.__isPromisified__ = true; \n\ - return ret; \n\ - " - .replace("FunctionName", callbackName) - .replace("Parameters", parameterDeclaration(newParameterCount)) - .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()))( - Promise, - callback, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - INTERNAL - ); -} - -function makeNodePromisifiedClosure(callback, receiver) { - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - if (typeof callback === "string") { - callback = _receiver[callback]; - } - var promise = new Promise(INTERNAL); - promise._setTrace(void 0); - var fn = nodebackForPromise(promise); - try { - callback.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - var wrapped = maybeWrapAsError(e); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } - return promise; - } - promisified.__isPromisified__ = true; - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - obj[promisifiedKey] = promisifier === makeNodePromisified - ? makeNodePromisified(key, THIS, key, fn, suffix) - : promisifier(fn); - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver) { - return makeNodePromisified(callback, receiver, void 0, callback); -} - -Promise.promisify = function Promise$Promisify(fn, receiver) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); - } - if (isPromisified(fn)) { - return fn; - } - return promisify(fn, arguments.length < 2 ? THIS : receiver); -}; - -Promise.promisifyAll = function Promise$PromisifyAll(target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function"); - } - options = Object(options); - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier"); - } - - var keys = util.inheritedDataKeys(target, {includeHidden: true}); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier); - promisifyAll(value, suffix, filter, promisifier); - } - } - - return promisifyAll(target, suffix, filter, promisifier); -}; -}; - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/props.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/props.js deleted file mode 100644 index 9da9859..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/props.js +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, cast) { -var util = require("./util.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var isObject = util.isObject; -var es5 = require("./es5.js"); - -function PropertiesPromiseArray(obj) { - var keys = es5.keys(obj); - var len = keys.length; - var values = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - values[i] = obj[key]; - values[i + len] = key; - } - this.constructor$(values); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = -function PropertiesPromiseArray$_init() { - this._init$(void 0, -3) ; -}; - -PropertiesPromiseArray.prototype._promiseFulfilled = -function PropertiesPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - this._resolve(val); - } -}; - -PropertiesPromiseArray.prototype._promiseProgressed = -function PropertiesPromiseArray$_promiseProgressed(value, index) { - if (this._isResolved()) return; - - this._promise._progress({ - key: this._values[index + this.length()], - value: value - }); -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = -function PropertiesPromiseArray$_shouldCopyValues() { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = -function PropertiesPromiseArray$getActualLength(len) { - return len >> 1; -}; - -function Promise$_Props(promises) { - var ret; - var castValue = cast(promises, void 0); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object"); - } else if (castValue instanceof Promise) { - ret = castValue._then(Promise.props, void 0, void 0, void 0, void 0); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 4); - } - return ret; -} - -Promise.prototype.props = function Promise$props() { - return Promise$_Props(this); -}; - -Promise.props = function Promise$Props(promises) { - return Promise$_Props(promises); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/queue.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/queue.js deleted file mode 100644 index d3dccdd..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/queue.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -function arrayCopy(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; - this._makeCapacity(); -} - -Queue.prototype._willBeOverCapacity = -function Queue$_willBeOverCapacity(size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function Queue$_pushOne(arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype.push = function Queue$push(fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function Queue$shift() { - var front = this._front, - ret = this[front]; - - this[front] = void 0; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function Queue$length() { - return this._length; -}; - -Queue.prototype._makeCapacity = function Queue$_makeCapacity() { - var len = this._capacity; - for (var i = 0; i < len; ++i) { - this[i] = void 0; - } -}; - -Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 3); - } -}; - -Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) { - var oldFront = this._front; - var oldCapacity = this._capacity; - var oldQueue = new Array(oldCapacity); - var length = this.length(); - - arrayCopy(this, 0, oldQueue, 0, oldCapacity); - this._capacity = capacity; - this._makeCapacity(); - this._front = 0; - if (oldFront + length <= oldCapacity) { - arrayCopy(oldQueue, oldFront, this, 0, length); - } else { var lengthBeforeWrapping = - length - ((oldFront + length) & (oldCapacity - 1)); - - arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping); - arrayCopy(oldQueue, 0, this, lengthBeforeWrapping, - length - lengthBeforeWrapping); - } -}; - -module.exports = Queue; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/race.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/race.js deleted file mode 100644 index 4e4c30e..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/race.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, cast) { -var apiRejection = require("./errors_api_rejection.js")(Promise); -var isArray = require("./util.js").isArray; - -var raceLater = function Promise$_raceLater(promise) { - return promise.then(function(array) { - return Promise$_Race(array, promise); - }); -}; - -var hasOwn = {}.hasOwnProperty; -function Promise$_Race(promises, parent) { - var maybePromise = cast(promises, void 0); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else if (!isArray(promises)) { - return apiRejection("expecting an array, a promise or a thenable"); - } - - var ret = new Promise(INTERNAL); - if (parent !== void 0) { - ret._propagateFrom(parent, 7); - } else { - ret._setTrace(void 0); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === void 0 && !(hasOwn.call(promises, i))) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, void 0, ret, null); - } - return ret; -} - -Promise.race = function Promise$Race(promises) { - return Promise$_Race(promises, void 0); -}; - -Promise.prototype.race = function Promise$race() { - return Promise$_Race(this, void 0); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/reduce.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/reduce.js deleted file mode 100644 index 30f2f05..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/reduce.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, cast, INTERNAL) { -var util = require("./util.js"); -var tryCatch4 = util.tryCatch4; -var tryCatch3 = util.tryCatch3; -var errorObj = util.errorObj; -function ReductionPromiseArray(promises, fn, accum, _each) { - this.constructor$(promises); - this._preservedValues = _each === INTERNAL ? [] : null; - this._zerothIsAccum = (accum === void 0); - this._gotAccum = false; - this._reducingIndex = (this._zerothIsAccum ? 1 : 0); - this._valuesPhase = undefined; - - var maybePromise = cast(accum, void 0); - var rejected = false; - var isPromise = maybePromise instanceof Promise; - if (isPromise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, -1); - } else if (maybePromise.isFulfilled()) { - accum = maybePromise.value(); - this._gotAccum = true; - } else { - maybePromise._unsetRejectionIsUnhandled(); - this._reject(maybePromise.reason()); - rejected = true; - } - } - if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; - this._callback = fn; - this._accum = accum; - if (!rejected) this._init$(void 0, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._init = -function ReductionPromiseArray$_init() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = -function ReductionPromiseArray$_resolveEmptyArray() { - if (this._gotAccum || this._zerothIsAccum) { - this._resolve(this._preservedValues !== null - ? [] : this._accum); - } -}; - -ReductionPromiseArray.prototype._promiseFulfilled = -function ReductionPromiseArray$_promiseFulfilled(value, index) { - var values = this._values; - if (values === null) return; - var length = this.length(); - var preservedValues = this._preservedValues; - var isEach = preservedValues !== null; - var gotAccum = this._gotAccum; - var valuesPhase = this._valuesPhase; - var valuesPhaseIndex; - if (!valuesPhase) { - valuesPhase = this._valuesPhase = Array(length); - for (valuesPhaseIndex=0; valuesPhaseIndex - * - * 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. - * - */ -"use strict"; -var schedule; -var _MutationObserver; -if (typeof process === "object" && typeof process.version === "string") { - schedule = function Promise$_Scheduler(fn) { - process.nextTick(fn); - }; -} -else if ((typeof MutationObserver !== "undefined" && - (_MutationObserver = MutationObserver)) || - (typeof WebKitMutationObserver !== "undefined" && - (_MutationObserver = WebKitMutationObserver))) { - schedule = (function() { - var div = document.createElement("div"); - var queuedFn = void 0; - var observer = new _MutationObserver( - function Promise$_Scheduler() { - var fn = queuedFn; - queuedFn = void 0; - fn(); - } - ); - observer.observe(div, { - attributes: true - }); - return function Promise$_Scheduler(fn) { - queuedFn = fn; - div.classList.toggle("foo"); - }; - - })(); -} -else if (typeof setTimeout !== "undefined") { - schedule = function Promise$_Scheduler(fn) { - setTimeout(fn, 0); - }; -} -else throw new Error("no async scheduler available"); -module.exports = schedule; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/settle.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/settle.js deleted file mode 100644 index 9881297..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/settle.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = - function(Promise, PromiseArray) { -var PromiseInspection = Promise.PromiseInspection; -var util = require("./util.js"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = -function SettledPromiseArray$_promiseResolved(index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -SettledPromiseArray.prototype._promiseFulfilled = -function SettledPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; - var ret = new PromiseInspection(); - ret._bitField = 268435456; - ret._settledValue = value; - this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = -function SettledPromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; - var ret = new PromiseInspection(); - ret._bitField = 134217728; - ret._settledValue = reason; - this._promiseResolved(index, ret); -}; - -Promise.settle = function Promise$Settle(promises) { - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function Promise$settle() { - return new SettledPromiseArray(this).promise(); -}; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/some.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/some.js deleted file mode 100644 index dba7183..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/some.js +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = require("./util.js"); -var RangeError = require("./errors.js").RangeError; -var AggregateError = require("./errors.js").AggregateError; -var isArray = util.isArray; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function SomePromiseArray$_init() { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(void 0, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function SomePromiseArray$init() { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = -function SomePromiseArray$setHowMany(count) { - if (this._isResolved()) return; - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = -function SomePromiseArray$_promiseFulfilled(value) { - if (this._isResolved()) return; - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - } - -}; -SomePromiseArray.prototype._promiseRejected = -function SomePromiseArray$_promiseRejected(reason) { - if (this._isResolved()) return; - this._addRejected(reason); - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - e.push(this._values[i]); - } - this._reject(e); - } -}; - -SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = -function SomePromiseArray$_addRejected(reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = -function SomePromiseArray$_addFulfilled(value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = -function SomePromiseArray$_canPossiblyFulfill() { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = -function SomePromiseArray$_getRangeError(count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = -function SomePromiseArray$_resolveEmptyArray() { - this._reject(this._getRangeError(0)); -}; - -function Promise$_Some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function Promise$Some(promises, howMany) { - return Promise$_Some(promises, howMany); -}; - -Promise.prototype.some = function Promise$some(howMany) { - return Promise$_Some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/synchronous_inspection.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/synchronous_inspection.js deleted file mode 100644 index 3c84020..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/synchronous_inspection.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== void 0) { - this._bitField = promise._bitField; - this._settledValue = promise.isResolved() - ? promise._settledValue - : void 0; - } - else { - this._bitField = 0; - this._settledValue = void 0; - } -} - -PromiseInspection.prototype.isFulfilled = -Promise.prototype.isFulfilled = function Promise$isFulfilled() { - return (this._bitField & 268435456) > 0; -}; - -PromiseInspection.prototype.isRejected = -Promise.prototype.isRejected = function Promise$isRejected() { - return (this._bitField & 134217728) > 0; -}; - -PromiseInspection.prototype.isPending = -Promise.prototype.isPending = function Promise$isPending() { - return (this._bitField & 402653184) === 0; -}; - -PromiseInspection.prototype.value = -Promise.prototype.value = function Promise$value() { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = -Promise.prototype.reason = function Promise$reason() { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.isResolved = -Promise.prototype.isResolved = function Promise$isResolved() { - return (this._bitField & 402653184) > 0; -}; - -Promise.PromiseInspection = PromiseInspection; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/thenables.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/thenables.js deleted file mode 100644 index 09e0266..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/thenables.js +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = require("./util.js"); -var canAttach = require("./errors.js").canAttach; -var errorObj = util.errorObj; -var isObject = util.isObject; - -function getThen(obj) { - try { - return obj.then; - } - catch(e) { - errorObj.e = e; - return errorObj; - } -} - -function Promise$_Cast(obj, originalPromise) { - if (isObject(obj)) { - if (obj instanceof Promise) { - return obj; - } - else if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - ret._setTrace(void 0); - obj._then( - ret._fulfillUnchecked, - ret._rejectUncheckedCheckError, - ret._progressUnchecked, - ret, - null - ); - ret._setFollowing(); - return ret; - } - var then = getThen(obj); - if (then === errorObj) { - if (originalPromise !== void 0 && canAttach(then.e)) { - originalPromise._attachExtraTrace(then.e); - } - return Promise.reject(then.e); - } else if (typeof then === "function") { - return Promise$_doThenable(obj, then, originalPromise); - } - } - return obj; -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - return hasProp.call(obj, "_promise0"); -} - -function Promise$_doThenable(x, then, originalPromise) { - var resolver = Promise.defer(); - var called = false; - try { - then.call( - x, - Promise$_resolveFromThenable, - Promise$_rejectFromThenable, - Promise$_progressFromThenable - ); - } catch(e) { - if (!called) { - called = true; - var trace = canAttach(e) ? e : new Error(e + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); - } - resolver.promise._reject(e, trace); - } - } - return resolver.promise; - - function Promise$_resolveFromThenable(y) { - if (called) return; - called = true; - - if (x === y) { - var e = Promise._makeSelfResolutionError(); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(e); - } - resolver.promise._reject(e, void 0); - return; - } - resolver.resolve(y); - } - - function Promise$_rejectFromThenable(r) { - if (called) return; - called = true; - var trace = canAttach(r) ? r : new Error(r + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); - } - resolver.promise._reject(r, trace); - } - - function Promise$_progressFromThenable(v) { - if (called) return; - var promise = resolver.promise; - if (typeof promise._progress === "function") { - promise._progress(v); - } - } -} - -return Promise$_Cast; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/timers.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/timers.js deleted file mode 100644 index 2d35221..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/timers.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var _setTimeout = function(fn, ms) { - var len = arguments.length; - var arg0 = arguments[2]; - var arg1 = arguments[3]; - var arg2 = len >= 5 ? arguments[4] : void 0; - setTimeout(function() { - fn(arg0, arg1, arg2); - }, ms|0); -}; - -module.exports = function(Promise, INTERNAL, cast) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var TimeoutError = Promise.TimeoutError; - -var afterTimeout = function Promise$_afterTimeout(promise, message, ms) { - if (!promise.isPending()) return; - if (typeof message !== "string") { - message = "operation timed out after" + " " + ms + " ms" - } - var err = new TimeoutError(message); - errors.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._cancel(err); -}; - -var afterDelay = function Promise$_afterDelay(value, promise) { - promise._fulfill(value); -}; - -var delay = Promise.delay = function Promise$Delay(value, ms) { - if (ms === void 0) { - ms = value; - value = void 0; - } - ms = +ms; - var maybePromise = cast(value, void 0); - var promise = new Promise(INTERNAL); - - if (maybePromise instanceof Promise) { - promise._propagateFrom(maybePromise, 7); - promise._follow(maybePromise); - return promise.then(function(value) { - return Promise.delay(value, ms); - }); - } else { - promise._setTrace(void 0); - _setTimeout(afterDelay, ms, value, promise); - } - return promise; -}; - -Promise.prototype.delay = function Promise$delay(ms) { - return delay(this, ms); -}; - -Promise.prototype.timeout = function Promise$timeout(ms, message) { - ms = +ms; - - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 7); - ret._follow(this); - _setTimeout(afterTimeout, ms, ret, message, ms); - return ret.cancellable(); -}; - -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/util.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/util.js deleted file mode 100644 index 0fadbc3..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/js/zalgo/util.js +++ /dev/null @@ -1,268 +0,0 @@ -/** - * Copyright (c) 2014 Petka Antonov - * - * 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. - * - */ -"use strict"; -var es5 = require("./es5.js"); -var haveGetters = (function(){ - try { - var o = {}; - es5.defineProperty(o, "f", { - get: function () { - return 3; - } - }); - return o.f === 3; - } - catch (e) { - return false; - } - -})(); -var canEvaluate = typeof navigator == "undefined"; -var errorObj = {e: {}}; -function tryCatch1(fn, receiver, arg) { - try { return fn.call(receiver, arg); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch2(fn, receiver, arg, arg2) { - try { return fn.call(receiver, arg, arg2); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch3(fn, receiver, arg, arg2, arg3) { - try { return fn.call(receiver, arg, arg2, arg3); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch4(fn, receiver, arg, arg2, arg3, arg4) { - try { return fn.call(receiver, arg, arg2, arg3, arg4); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatchApply(fn, args, receiver) { - try { return fn.apply(receiver, args); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - -function asString(val) { - return typeof val === "string" ? val : ("" + val); -} - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return !isPrimitive(value); -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(asString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : void 0; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - - -var wrapsPrimitiveReceiver = (function() { - return this !== "string"; -}).call("string"); - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - if (es5.isES5) { - return function(obj, opts) { - var ret = []; - var visitedKeys = Object.create(null); - var getKeys = Object(opts).includeHidden - ? Object.getOwnPropertyNames - : Object.keys; - while (obj != null) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - return function(obj) { - var ret = []; - /*jshint forin:false */ - for (var key in obj) { - ret.push(key); - } - return ret; - }; - } - -})(); - -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.keys(fn.prototype); - return keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027*/ - function f() {} - f.prototype = obj; - return f; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - haveGetters: haveGetters, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch1: tryCatch1, - tryCatch2: tryCatch2, - tryCatch3: tryCatch3, - tryCatch4: tryCatch4, - tryCatchApply: tryCatchApply, - inherits: inherits, - withAppended: withAppended, - asString: asString, - maybeWrapAsError: maybeWrapAsError, - wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, - toFastProperties: toFastProperties, - filledRange: filledRange -}; - -module.exports = ret; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json deleted file mode 100644 index a5de3f1..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/package.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "name": "bluebird", - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "version": "2.3.2", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" - ], - "scripts": { - "test": "grunt test", - "prepublish": "grunt build" - }, - "homepage": "https://github.com/petkaantonov/bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" - }, - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "license": "MIT", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "devDependencies": { - "grunt": "~0.4.1", - "grunt-contrib-jshint": "~0.10.0", - "grunt-contrib-watch": "latest", - "grunt-contrib-connect": "latest", - "grunt-contrib-concat": "latest", - "grunt-saucelabs": "~8.3.1", - "acorn": "~0.6.0", - "mocha": "~1.20.1", - "q": "~1.0.1", - "when": "~3.2.3", - "deferred": "~0.7.1", - "rsvp": "~3.0.9", - "avow": "~2.0.1", - "jsdom": "~0.11.0", - "jquery-browserify": "~1.8.1", - "sinon": "~1.7.3", - "kew": "~0.4.0", - "browserify": "~4.2.0", - "concurrent": "~0.3.2", - "text-table": "~0.2.0", - "grunt-cli": "~0.1.9", - "jshint-stylish": "~0.2.0", - "semver-utils": "~1.1.0", - "rimraf": "~2.2.6", - "mkdirp": "~0.5.0" - }, - "main": "./js/main/bluebird.js", - "files": [ - "js/main", - "js/zalgo", - "LICENSE", - "zalgo.js" - ], - "_id": "bluebird@2.3.2", - "dist": { - "shasum": "7475ac7ca0c1674077ac3dd4092ddb80233cf26b", - "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.3.2.tgz" - }, - "_from": "bluebird@2.3.2", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "esailija", - "email": "petka_antonov@hotmail.com" - }, - "maintainers": [ - { - "name": "esailija", - "email": "petka_antonov@hotmail.com" - } - ], - "directories": {}, - "_shasum": "7475ac7ca0c1674077ac3dd4092ddb80233cf26b", - "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.3.2.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/zalgo.js b/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/zalgo.js deleted file mode 100644 index 1357352..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/bluebird/zalgo.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./js/zalgo/bluebird.js'); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js deleted file mode 100644 index 509dc0d..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js +++ /dev/null @@ -1,137 +0,0 @@ - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - fmt = coerce(fmt); - - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - try { - localStorage.debug = name; - } catch(e){} - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -/** - * Coerce `val`. - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - -// persist - -try { - if (window.localStorage) debug.enable(localStorage.debug); -} catch(e){} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js deleted file mode 100644 index e02c13b..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js +++ /dev/null @@ -1,5 +0,0 @@ -if ('undefined' == typeof window) { - module.exports = require('./lib/debug'); -} else { - module.exports = require('./debug'); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js deleted file mode 100644 index 3b0a918..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - fmt = coerce(fmt); - - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \u001b[9' + c + 'm' + name + ' ' - + '\u001b[3' + c + 'm\u001b[90m' - + fmt + '\u001b[3' + c + 'm' - + ' +' + humanize(ms) + '\u001b[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = coerce(fmt); - - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty || process.env.DEBUG_COLORS - ? colored - : plain; -} - -/** - * Coerce `val`. - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json deleted file mode 100644 index 882a300..0000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "name": "debug", - "version": "0.7.4", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "lib/debug.js", - "browser": "./debug.js", - "engines": { - "node": "*" - }, - "files": [ - "lib/debug.js", - "debug.js", - "index.js" - ], - "component": { - "scripts": { - "debug/index.js": "index.js", - "debug/debug.js": "debug.js" - } - }, - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@0.7.4", - "dist": { - "shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", - "tarball": "http://registry.npmjs.org/debug/-/debug-0.7.4.tgz" - }, - "_from": "debug@0.7.4", - "_npmVersion": "1.3.13", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - } - ], - "directories": {}, - "_shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", - "_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.4.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/mongoose/node_modules/mquery/package.json b/node_modules/mongoose/node_modules/mquery/package.json deleted file mode 100644 index 4101799..0000000 --- a/node_modules/mongoose/node_modules/mquery/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "mquery", - "version": "1.4.0", - "description": "Expressive query building for MongoDB", - "main": "lib/mquery.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mquery.git" - }, - "dependencies": { - "bluebird": "2.3.2", - "debug": "0.7.4", - "regexp-clone": "0.0.1", - "sliced": "0.0.5" - }, - "devDependencies": { - "mongodb": "1.4.12", - "mocha": "1.9.x", - "istanbul": "0.3.2" - }, - "bugs": { - "url": "https://github.com/aheckmann/mquery/issues/new" - }, - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "keywords": [ - "mongodb", - "query", - "builder" - ], - "homepage": "https://github.com/aheckmann/mquery/", - "gitHead": "43ace72da53b63e82b21380432b2e61169c98225", - "_id": "mquery@1.4.0", - "_shasum": "d49b1c1ca89d1a06ebb6f000316fadba56c2469d", - "_from": "mquery@1.4.0", - "_npmVersion": "1.4.28", - "_npmUser": { - "name": "vkarpov15", - "email": "valkar207@gmail.com" - }, - "maintainers": [ - { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - }, - { - "name": "ebensing", - "email": "ebensing38@gmail.com" - }, - { - "name": "vkarpov15", - "email": "valkar207@gmail.com" - } - ], - "dist": { - "shasum": "d49b1c1ca89d1a06ebb6f000316fadba56c2469d", - "tarball": "http://registry.npmjs.org/mquery/-/mquery-1.4.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.4.0.tgz" -} diff --git a/node_modules/mongoose/node_modules/sliced/package.json b/node_modules/mongoose/node_modules/sliced/package.json deleted file mode 100644 index 4fb669a..0000000 --- a/node_modules/mongoose/node_modules/sliced/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "sliced", - "version": "0.0.5", - "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/sliced" - }, - "keywords": [ - "arguments", - "slice", - "array" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "devDependencies": { - "mocha": "1.5.0", - "benchmark": "~1.0.0" - }, - "readme": "#sliced\n==========\n\nA faster alternative to `[].slice.call(arguments)`.\n\n[![Build Status](https://secure.travis-ci.org/aheckmann/sliced.png)](http://travis-ci.org/aheckmann/sliced)\n\nExample output from [benchmark.js](https://github.com/bestiejs/benchmark.js)\n\n Array.prototype.slice.call x 1,320,205 ops/sec ±2.35% (92 runs sampled)\n [].slice.call x 1,314,605 ops/sec ±1.60% (95 runs sampled)\n cached slice.call x 10,468,380 ops/sec ±1.45% (95 runs sampled)\n sliced x 16,608,237 ops/sec ±1.40% (92 runs sampled)\n fastest is sliced\n\n Array.prototype.slice.call(arguments, 1) x 1,383,584 ops/sec ±1.73% (97 runs sampled)\n [].slice.call(arguments, 1) x 1,494,735 ops/sec ±1.33% (95 runs sampled)\n cached slice.call(arguments, 1) x 10,085,270 ops/sec ±1.51% (97 runs sampled)\n sliced(arguments, 1) x 16,620,480 ops/sec ±1.29% (95 runs sampled)\n fastest is sliced(arguments, 1)\n\n Array.prototype.slice.call(arguments, -1) x 1,303,262 ops/sec ±1.62% (94 runs sampled)\n [].slice.call(arguments, -1) x 1,325,615 ops/sec ±1.36% (97 runs sampled)\n cached slice.call(arguments, -1) x 9,673,603 ops/sec ±1.70% (96 runs sampled)\n sliced(arguments, -1) x 16,384,575 ops/sec ±1.06% (91 runs sampled)\n fastest is sliced(arguments, -1)\n\n Array.prototype.slice.call(arguments, -2, -10) x 1,404,390 ops/sec ±1.61% (95 runs sampled)\n [].slice.call(arguments, -2, -10) x 1,514,367 ops/sec ±1.21% (96 runs sampled)\n cached slice.call(arguments, -2, -10) x 9,836,017 ops/sec ±1.21% (95 runs sampled)\n sliced(arguments, -2, -10) x 18,544,882 ops/sec ±1.30% (91 runs sampled)\n fastest is sliced(arguments, -2, -10)\n\n Array.prototype.slice.call(arguments, -2, -1) x 1,458,604 ops/sec ±1.41% (97 runs sampled)\n [].slice.call(arguments, -2, -1) x 1,536,547 ops/sec ±1.63% (99 runs sampled)\n cached slice.call(arguments, -2, -1) x 10,060,633 ops/sec ±1.37% (96 runs sampled)\n sliced(arguments, -2, -1) x 18,608,712 ops/sec ±1.08% (93 runs sampled)\n fastest is sliced(arguments, -2, -1)\n\n_Benchmark [source](https://github.com/aheckmann/sliced/blob/master/bench.js)._\n\n##Usage\n\n`sliced` accepts the same arguments as `Array#slice` so you can easily swap it out.\n\n```js\nfunction zing () {\n var slow = [].slice.call(arguments, 1, 8);\n var args = slice(arguments, 1, 8);\n\n var slow = Array.prototype.slice.call(arguments);\n var args = slice(arguments);\n // etc\n}\n```\n\n## install\n\n npm install sliced\n\n\n[LICENSE](https://github.com/aheckmann/sliced/blob/master/LICENSE)\n", - "_id": "sliced@0.0.5", - "dist": { - "shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", - "tarball": "http://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz" - }, - "_npmVersion": "1.1.59", - "_npmUser": { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - }, - "maintainers": [ - { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - } - ], - "directories": {}, - "_shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", - "_resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", - "_from": "sliced@0.0.5" -} diff --git a/node_modules/mongoose/package.json b/node_modules/mongoose/package.json index 00a1361..f99003a 100644 --- a/node_modules/mongoose/package.json +++ b/node_modules/mongoose/package.json @@ -1,107 +1,96 @@ { - "name": "mongoose", - "description": "Mongoose MongoDB ODM", - "version": "3.8.29", + "_from": "mongoose@3.8.40", + "_id": "mongoose@3.8.40", + "_inBundle": false, + "_integrity": "sha1-Ay9bpVWCSXVZqHwfP0s5WcJkBqc=", + "_location": "/mongoose", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongoose@3.8.40", + "name": "mongoose", + "escapedName": "mongoose", + "rawSpec": "3.8.40", + "saveSpec": null, + "fetchSpec": "3.8.40" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "http://registry.npmjs.org/mongoose/-/mongoose-3.8.40.tgz", + "_shasum": "032f5ba55582497559a87c1f3f4b3959c26406a7", + "_spec": "mongoose@3.8.40", + "_where": "E:\\github\\node-dc-mongo", "author": { "name": "Guillermo Rauch", "email": "guillermo@learnboost.com" }, - "keywords": [ - "mongodb", - "document", - "model", - "schema", - "database", - "odm", - "data", - "datastore", - "query", - "nosql", - "orm", - "db" - ], + "bugs": { + "url": "https://github.com/learnboost/mongoose/issues/new", + "email": "mongoose-orm@googlegroups.com" + }, + "bundleDependencies": false, "dependencies": { - "mongodb": "1.4.32", "hooks": "0.2.1", + "mongodb": "1.4.38", + "mpath": "0.1.1", + "mpromise": "0.4.3", + "mquery": "1.10.0", "ms": "0.1.0", - "sliced": "0.0.5", "muri": "1.1.0", - "mpromise": "0.4.3", - "mpath": "0.1.1", "regexp-clone": "0.0.1", - "mquery": "1.4.0" + "sliced": "0.0.5" }, + "deprecated": false, + "description": "Mongoose MongoDB ODM", "devDependencies": { - "mocha": "1.12.0", - "node-static": "0.5.9", + "async": "0.2.5", + "benchmark": "1.0.0", "dox": "0.3.1", - "jade": "0.26.3", "highlight.js": "7.0.1", + "jade": "0.26.3", "markdown": "0.3.1", + "mocha": "1.12.0", + "node-static": "0.5.9", + "open": "0.0.3", "promises-aplus-tests": "2.0.4", "tbd": "0.6.4", - "benchmark": "1.0.0", - "open": "0.0.3", - "async": "0.2.5", "underscore": "1.5.2" }, "directories": { "lib": "./lib/mongoose" }, - "scripts": { - "test": "make test" - }, - "main": "./index.js", "engines": { "node": ">=0.6.19" }, - "bugs": { - "url": "https://github.com/learnboost/mongoose/issues/new", - "email": "mongoose-orm@googlegroups.com" - }, - "repository": { - "type": "git", - "url": "git://github.com/LearnBoost/mongoose.git" - }, "homepage": "http://mongoosejs.com", + "keywords": [ + "mongodb", + "document", + "model", + "schema", + "database", + "odm", + "data", + "datastore", + "query", + "nosql", + "orm", + "db" + ], + "main": "./index.js", + "name": "mongoose", "publishConfig": { "tag": "legacy" }, - "gitHead": "4f15edd5133c96610b2d605f6abea216773933d5", - "_id": "mongoose@3.8.29", - "_shasum": "6b597e5cf87e708da6bcd3b1eb6dc92814e1bfe3", - "_from": "mongoose@>=3.8.0 <3.9.0", - "_npmVersion": "2.7.4", - "_nodeVersion": "0.12.2", - "_npmUser": { - "name": "vkarpov15", - "email": "valkar207@gmail.com" + "repository": { + "type": "git", + "url": "git://github.com/LearnBoost/mongoose.git" }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - }, - { - "name": "vkarpov15", - "email": "val@karpov.io" - }, - { - "name": "defunctzombie", - "email": "shtylman@gmail.com" - } - ], - "dist": { - "shasum": "6b597e5cf87e708da6bcd3b1eb6dc92814e1bfe3", - "tarball": "http://registry.npmjs.org/mongoose/-/mongoose-3.8.29.tgz" + "scripts": { + "test": "make test" }, - "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-3.8.29.tgz" + "version": "3.8.40" } diff --git a/node_modules/mongoose/node_modules/mpath/.npmignore b/node_modules/mpath/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/mpath/.npmignore rename to node_modules/mpath/.npmignore diff --git a/node_modules/mongoose/node_modules/mpath/.travis.yml b/node_modules/mpath/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/mpath/.travis.yml rename to node_modules/mpath/.travis.yml diff --git a/node_modules/mongoose/node_modules/mpath/History.md b/node_modules/mpath/History.md similarity index 100% rename from node_modules/mongoose/node_modules/mpath/History.md rename to node_modules/mpath/History.md diff --git a/node_modules/mongoose/node_modules/mpath/LICENSE b/node_modules/mpath/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mpath/LICENSE rename to node_modules/mpath/LICENSE diff --git a/node_modules/mongoose/node_modules/mpath/Makefile b/node_modules/mpath/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/mpath/Makefile rename to node_modules/mpath/Makefile diff --git a/node_modules/mongoose/node_modules/mpath/README.md b/node_modules/mpath/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mpath/README.md rename to node_modules/mpath/README.md diff --git a/node_modules/mongoose/node_modules/mpath/index.js b/node_modules/mpath/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mpath/index.js rename to node_modules/mpath/index.js diff --git a/node_modules/mongoose/node_modules/mpath/lib/index.js b/node_modules/mpath/lib/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mpath/lib/index.js rename to node_modules/mpath/lib/index.js diff --git a/node_modules/mongoose/node_modules/mpath/package.json b/node_modules/mpath/package.json similarity index 55% rename from node_modules/mongoose/node_modules/mpath/package.json rename to node_modules/mpath/package.json index 8f52706..3dc908a 100644 --- a/node_modules/mongoose/node_modules/mpath/package.json +++ b/node_modules/mpath/package.json @@ -1,47 +1,72 @@ { - "name": "mpath", - "version": "0.1.1", - "description": "{G,S}et object values using MongoDB path notation", - "main": "index.js", - "scripts": { - "test": "make test" + "_from": "mpath@0.1.1", + "_id": "mpath@0.1.1", + "_inBundle": false, + "_integrity": "sha1-I9qFK3wjLuCX9HWdKcDunNItXkY=", + "_location": "/mpath", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpath.git" + "_npmVersion": "1.1.59", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mpath@0.1.1", + "name": "mpath", + "escapedName": "mpath", + "rawSpec": "0.1.1", + "saveSpec": null, + "fetchSpec": "0.1.1" }, - "keywords": [ - "mongodb", - "path", - "get", - "set" + "_requiredBy": [ + "/mongoose" ], + "_resolved": "http://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz", + "_shasum": "23da852b7c232ee097f4759d29c0ee9cd22d5e46", + "_spec": "mpath@0.1.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", "author": { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - "license": "MIT", + "bugs": { + "url": "https://github.com/aheckmann/mpath/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "{G,S}et object values using MongoDB path notation", "devDependencies": { "mocha": "1.6.0" }, - "_id": "mpath@0.1.1", + "directories": {}, "dist": { "shasum": "23da852b7c232ee097f4759d29c0ee9cd22d5e46", "tarball": "http://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz" }, - "_npmVersion": "1.1.59", - "_npmUser": { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - }, + "homepage": "https://github.com/aheckmann/mpath#readme", + "keywords": [ + "mongodb", + "path", + "get", + "set" + ], + "license": "MIT", + "main": "index.js", "maintainers": [ { "name": "aaron", "email": "aaron.heckmann+github@gmail.com" } ], - "directories": {}, - "_shasum": "23da852b7c232ee097f4759d29c0ee9cd22d5e46", - "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz", - "_from": "mpath@0.1.1" + "name": "mpath", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpath.git" + }, + "scripts": { + "test": "make test" + }, + "version": "0.1.1" } diff --git a/node_modules/mongoose/node_modules/mpath/test/index.js b/node_modules/mpath/test/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mpath/test/index.js rename to node_modules/mpath/test/index.js diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/.name b/node_modules/mpromise/.idea/.name similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/.name rename to node_modules/mpromise/.idea/.name diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/codeStyleSettings.xml b/node_modules/mpromise/.idea/codeStyleSettings.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/codeStyleSettings.xml rename to node_modules/mpromise/.idea/codeStyleSettings.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/encodings.xml b/node_modules/mpromise/.idea/encodings.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/encodings.xml rename to node_modules/mpromise/.idea/encodings.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml b/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml rename to node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml b/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml rename to node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/jsLibraryMappings.xml b/node_modules/mpromise/.idea/jsLibraryMappings.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/jsLibraryMappings.xml rename to node_modules/mpromise/.idea/jsLibraryMappings.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml b/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml rename to node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/misc.xml b/node_modules/mpromise/.idea/misc.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/misc.xml rename to node_modules/mpromise/.idea/misc.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/modules.xml b/node_modules/mpromise/.idea/modules.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/modules.xml rename to node_modules/mpromise/.idea/modules.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/mpromise.iml b/node_modules/mpromise/.idea/mpromise.iml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/mpromise.iml rename to node_modules/mpromise/.idea/mpromise.iml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/other.xml b/node_modules/mpromise/.idea/other.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/other.xml rename to node_modules/mpromise/.idea/other.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/scopes/scope_settings.xml b/node_modules/mpromise/.idea/scopes/scope_settings.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/scopes/scope_settings.xml rename to node_modules/mpromise/.idea/scopes/scope_settings.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/vcs.xml b/node_modules/mpromise/.idea/vcs.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/vcs.xml rename to node_modules/mpromise/.idea/vcs.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/workspace.xml b/node_modules/mpromise/.idea/workspace.xml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.idea/workspace.xml rename to node_modules/mpromise/.idea/workspace.xml diff --git a/node_modules/mongoose/node_modules/mpromise/.npmignore b/node_modules/mpromise/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.npmignore rename to node_modules/mpromise/.npmignore diff --git a/node_modules/mongoose/node_modules/mpromise/.travis.yml b/node_modules/mpromise/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/.travis.yml rename to node_modules/mpromise/.travis.yml diff --git a/node_modules/mongoose/node_modules/mpromise/History.md b/node_modules/mpromise/History.md similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/History.md rename to node_modules/mpromise/History.md diff --git a/node_modules/mongoose/node_modules/mpromise/LICENSE b/node_modules/mpromise/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/LICENSE rename to node_modules/mpromise/LICENSE diff --git a/node_modules/mongoose/node_modules/mpromise/README.md b/node_modules/mpromise/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/README.md rename to node_modules/mpromise/README.md diff --git a/node_modules/mongoose/node_modules/mpromise/index.js b/node_modules/mpromise/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/index.js rename to node_modules/mpromise/index.js diff --git a/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/node_modules/mpromise/lib/promise.js similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/lib/promise.js rename to node_modules/mpromise/lib/promise.js diff --git a/node_modules/mongoose/node_modules/mpromise/package.json b/node_modules/mpromise/package.json similarity index 64% rename from node_modules/mongoose/node_modules/mpromise/package.json rename to node_modules/mpromise/package.json index 3e376a3..5c802dc 100644 --- a/node_modules/mongoose/node_modules/mpromise/package.json +++ b/node_modules/mpromise/package.json @@ -1,47 +1,62 @@ { - "name": "mpromise", - "version": "0.4.3", - "description": "Promises A+ conformant implementation", - "main": "index.js", - "scripts": { - "test": "node node_modules/mocha/bin/_mocha" - }, - "devDependencies": { - "longjohn": "~0.2.1", - "promises-aplus-tests": "~2.0.2", - "mocha": "~1.13.0" + "_from": "mpromise@0.4.3", + "_id": "mpromise@0.4.3", + "_inBundle": false, + "_integrity": "sha1-7cR6daKhd7DpOCc121Lb7DgIzDM=", + "_location": "/mpromise", + "_npmUser": { + "name": "refack", + "email": "refael@empeeric.com" }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpromise" + "_npmVersion": "1.3.13", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mpromise@0.4.3", + "name": "mpromise", + "escapedName": "mpromise", + "rawSpec": "0.4.3", + "saveSpec": null, + "fetchSpec": "0.4.3" }, - "keywords": [ - "promise", - "mongoose", - "aplus", - "a+", - "plus" + "_requiredBy": [ + "/mongoose" ], + "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.4.3.tgz", + "_shasum": "edc47a75a2a177b0e9382735db52dbec3808cc33", + "_spec": "mpromise@0.4.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", "author": { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - "license": "MIT", "bugs": { "url": "https://github.com/aheckmann/mpromise/issues" }, - "homepage": "https://github.com/aheckmann/mpromise", - "_id": "mpromise@0.4.3", + "bundleDependencies": false, + "deprecated": false, + "description": "Promises A+ conformant implementation", + "devDependencies": { + "longjohn": "~0.2.1", + "mocha": "~1.13.0", + "promises-aplus-tests": "~2.0.2" + }, + "directories": {}, "dist": { "shasum": "edc47a75a2a177b0e9382735db52dbec3808cc33", "tarball": "http://registry.npmjs.org/mpromise/-/mpromise-0.4.3.tgz" }, - "_from": "mpromise@0.4.3", - "_npmVersion": "1.3.13", - "_npmUser": { - "name": "refack", - "email": "refael@empeeric.com" - }, + "homepage": "https://github.com/aheckmann/mpromise", + "keywords": [ + "promise", + "mongoose", + "aplus", + "a+", + "plus" + ], + "license": "MIT", + "main": "index.js", "maintainers": [ { "name": "aaron", @@ -52,7 +67,13 @@ "email": "refael@empeeric.com" } ], - "directories": {}, - "_shasum": "edc47a75a2a177b0e9382735db52dbec3808cc33", - "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.4.3.tgz" + "name": "mpromise", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mpromise.git" + }, + "scripts": { + "test": "node node_modules/mocha/bin/_mocha" + }, + "version": "0.4.3" } diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js b/node_modules/mpromise/test/promise.domain.test.js similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js rename to node_modules/mpromise/test/promise.domain.test.js diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/node_modules/mpromise/test/promise.test.js similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/test/promise.test.js rename to node_modules/mpromise/test/promise.test.js diff --git a/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js b/node_modules/mpromise/test/promises.Aplus.js similarity index 100% rename from node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js rename to node_modules/mpromise/test/promises.Aplus.js diff --git a/node_modules/mongoose/node_modules/mquery/.npmignore b/node_modules/mquery/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/mquery/.npmignore rename to node_modules/mquery/.npmignore diff --git a/node_modules/mongoose/node_modules/mquery/.travis.yml b/node_modules/mquery/.travis.yml similarity index 56% rename from node_modules/mongoose/node_modules/mquery/.travis.yml rename to node_modules/mquery/.travis.yml index 4dc3a7d..54f54a5 100644 --- a/node_modules/mongoose/node_modules/mquery/.travis.yml +++ b/node_modules/mquery/.travis.yml @@ -1,7 +1,8 @@ language: node_js node_js: - - 0.8 - - 0.10 - - 0.11 + - "0.10" + - "0.12" + - "4" + - "5" services: - mongodb diff --git a/node_modules/mongoose/node_modules/mquery/History.md b/node_modules/mquery/History.md similarity index 78% rename from node_modules/mongoose/node_modules/mquery/History.md rename to node_modules/mquery/History.md index 90567f3..920eba6 100644 --- a/node_modules/mongoose/node_modules/mquery/History.md +++ b/node_modules/mquery/History.md @@ -1,4 +1,51 @@ +1.10.0 / 2016-03-16 +================== + + * updated; bluebird to latest 2.10.2 version #74 [matskiv](https://github.com/matskiv) + +1.9.0 / 2016-03-15 +================== + * added; `.eq` as a shortcut for `.equals` #72 [Fonger](https://github.com/Fonger) + * added; ability to use array syntax for sort re: https://jira.mongodb.org/browse/NODE-578 #67 + +1.8.0 / 2016-03-01 +================== + * fixed; dont throw an error if count used with sort or select Automattic/mongoose#3914 + +1.7.0 / 2016-02-23 +================== + * fixed; don't treat objects with a length property as argument objects #70 + * added; `.findCursor()` method #69 [nswbmw](https://github.com/nswbmw) + * added; `_compiledUpdate` property #68 [nswbmw](https://github.com/nswbmw) + +1.6.2 / 2015-07-12 +================== + + * fixed; support exec cb being called synchronously #66 + +1.6.1 / 2015-06-16 +================== + + * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) + +1.6.0 / 2015-05-27 +================== + + * update dependencies #65 [bachp](https://github.com/bachp) + +1.5.0 / 2015-03-31 +================== + + * fixed; debug output + * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) + +1.4.0 / 2015-03-29 +================== + + * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) + * debug; improved output #57 [flyvictor](https://github.com/flyvictor) + 1.3.0 / 2014-11-06 ================== @@ -126,7 +173,7 @@ 0.2.6 / 2013-07-30 ================== - * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively + * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively 0.2.5 / 2013-07-30 ================== diff --git a/node_modules/mongoose/node_modules/mquery/LICENSE b/node_modules/mquery/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/mquery/LICENSE rename to node_modules/mquery/LICENSE diff --git a/node_modules/mongoose/node_modules/mquery/Makefile b/node_modules/mquery/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/mquery/Makefile rename to node_modules/mquery/Makefile diff --git a/node_modules/mongoose/node_modules/mquery/README.md b/node_modules/mquery/README.md similarity index 100% rename from node_modules/mongoose/node_modules/mquery/README.md rename to node_modules/mquery/README.md diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/node_modules/mquery/lib/collection/collection.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/lib/collection/collection.js rename to node_modules/mquery/lib/collection/collection.js diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/node_modules/mquery/lib/collection/index.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/lib/collection/index.js rename to node_modules/mquery/lib/collection/index.js diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/node_modules/mquery/lib/collection/node.js similarity index 92% rename from node_modules/mongoose/node_modules/mquery/lib/collection/node.js rename to node_modules/mquery/lib/collection/node.js index f254456..ab248b8 100644 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js +++ b/node_modules/mquery/lib/collection/node.js @@ -87,6 +87,14 @@ NodeCollection.prototype.findStream = function(match, findOptions, streamOptions return this.collection.find(match, findOptions).stream(streamOptions); } +/** + * var cursor = findCursor(match, findOptions) + */ + +NodeCollection.prototype.findCursor = function(match, findOptions) { + return this.collection.find(match, findOptions); +} + /** * aggregation(operators..., function(err, doc)) * TODO diff --git a/node_modules/mongoose/node_modules/mquery/lib/env.js b/node_modules/mquery/lib/env.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/lib/env.js rename to node_modules/mquery/lib/env.js diff --git a/node_modules/mquery/lib/helper.js b/node_modules/mquery/lib/helper.js new file mode 100644 index 0000000..605da49 --- /dev/null +++ b/node_modules/mquery/lib/helper.js @@ -0,0 +1,30 @@ + +var debug = require('debug')('yield:inputhelper'); +var isObject = require('is-object'); +var hasOwn = require('has-own'); +var ObjectId = require('mongodb').ObjectID; + +exports.cast = function cast(arg) { + debug('cast %s', arg); + + if (!arg) return {}; + + // find(id) + if (isHexString(arg)) { + return { _id: new ObjectId(arg) }; + } + + if (!isObject(arg)) + throw new TypeError('invalid selector'); + + // find({ _id: '54049bff83359f9872f94c19' }) + if (arg._id && isHexString(arg._id)) { + arg._id = new ObjectId(arg._id); + } + + return arg; +} + +function isHexString(arg) { + return 24 == arg.length && 'string' == typeof arg; +} diff --git a/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/node_modules/mquery/lib/mquery.js similarity index 94% rename from node_modules/mongoose/node_modules/mquery/lib/mquery.js rename to node_modules/mquery/lib/mquery.js index 76a5854..6185e05 100644 --- a/node_modules/mongoose/node_modules/mquery/lib/mquery.js +++ b/node_modules/mquery/lib/mquery.js @@ -302,6 +302,34 @@ Query.prototype.equals = function equals (val) { return this; } +/** + * Specifies the complementary comparison value for paths specified with `where()` + * This is alias of `equals` + * + * ####Example + * + * User.where('age').eq(49); + * + * // is the same as + * + * User.shere('age').equals(49); + * + * // is the same as + * + * User.where('age', 49); + * + * @param {Object} val + * @return {Query} this + * @api public + */ + +Query.prototype.eq = function eq (val) { + this._ensurePath('eq'); + var path = this._path; + this._conditions[path] = val; + return this; +} + /** * Specifies arguments for an `$or` condition. * @@ -1074,7 +1102,8 @@ Query.prototype.select = function select () { var fields = this._fields || (this._fields = {}); var type = typeof arg; - if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { + if (('string' == type || utils.isArgumentsObject(arg)) && + 'number' == typeof arg.length) { if ('string' == type) arg = arg.split(/\s+/); @@ -1170,27 +1199,40 @@ Query.prototype.slice = function () { * // these are equivalent * query.sort({ field: 'asc', test: -1 }); * query.sort('field -test'); + * query.sort([['field', 1], ['test', -1]]); * * ####Note * - * Cannot be used with `distinct()` + * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). + * - Cannot be used with `distinct()` * - * @param {Object|String} arg + * @param {Object|String|Array} arg * @return {Query} this * @api public */ Query.prototype.sort = function (arg) { if (!arg) return this; + var len; this._validate('sort'); var type = typeof arg; + // .sort([['field', 1], ['test', -1]]) + if (Array.isArray(arg)) { + len = arg.length; + for (var i = 0; i < arg.length; ++i) { + _pushArr(this.options, arg[i][0], arg[i][1]); + } + return this; + } + + // .sort('field -test') if (1 === arguments.length && 'string' == type) { arg = arg.split(/\s+/); - - for (var i = 0, len = arg.length; i < len; ++i) { + len = arg.length; + for (var i = 0; i < len; ++i) { var field = arg[i]; if (!field) continue; var ascend = '-' == field[0] ? -1 : 1; @@ -1201,6 +1243,7 @@ Query.prototype.sort = function (arg) { return this; } + // .sort({ field: 1, test: -1 }) if (utils.isObject(arg)) { var keys = utils.keys(arg); for (var i = 0; i < keys.length; ++i) { @@ -1211,7 +1254,7 @@ Query.prototype.sort = function (arg) { return this; } - throw new TypeError('Invalid sort() argument. Must be a string or object.'); + throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); } /*! @@ -1219,6 +1262,12 @@ Query.prototype.sort = function (arg) { */ function push (opts, field, value) { + if (Array.isArray(opts.sort)) { + throw new TypeError("Can't mix sort syntaxes. Use either array or object:" + + "\n- `.sort([['field', 1], ['test', -1]])`" + + "\n- `.sort({ field: 1, test: -1 })`"); + } + if (value && value.$meta) { var s = opts.sort || (opts.sort = {}); s[field] = { $meta : value.$meta }; @@ -1240,6 +1289,21 @@ function push (opts, field, value) { s[field] = parseInt(valueStr, 10); } +function _pushArr (opts, field, value) { + opts.sort = opts.sort || []; + if (!Array.isArray(opts.sort)) { + throw new TypeError("Can't mix sort syntaxes. Use either array or object:" + + "\n- `.sort([['field', 1], ['test', -1]])`" + + "\n- `.sort({ field: 1, test: -1 })`"); + } + var valueStr = value.toString() + .replace("asc", "1") + .replace("ascending", "1") + .replace("desc", "-1") + .replace("descending", "-1"); + opts.sort.push([field, value]); +} + /** * Specifies the limit option. * @@ -1620,7 +1684,7 @@ Query.prototype.find = function (criteria, callback) { options.fields = this._fieldsForExec() - debug('find', this._collection.collection.name, conds, options); + debug('find', this._collection.collectionName, conds, options); callback = this._wrapCallback('find', callback, { conditions: conds , options: options @@ -1630,6 +1694,37 @@ Query.prototype.find = function (criteria, callback) { return this; } +/** + * Returns the query cursor + * + * ####Examples + * + * query.find().cursor(); + * query.cursor({ name: 'Burning Lights' }); + * + * @param {Object} [criteria] mongodb selector + * @return {Object} cursor + * @api public + */ + +Query.prototype.cursor = function cursor (criteria) { + if (this.op) { + if (this.op !== 'find') { + throw new TypeError(".cursor only support .find method"); + } + } else { + this.find(criteria); + } + + var conds = this._conditions + , options = this._optionsForExec() + + options.fields = this._fieldsForExec() + + debug('findCursor', this._collection.collectionName, conds, options); + return this._collection.findCursor(conds, options); +} + /** * Executes the query as a findOne() operation. * @@ -1675,7 +1770,7 @@ Query.prototype.findOne = function (criteria, callback) { options.fields = this._fieldsForExec(); - debug('findOne', this._collection.collection.name, conds, options); + debug('findOne', this._collection.collectionName, conds, options); callback = this._wrapCallback('findOne', callback, { conditions: conds , options: options @@ -1727,7 +1822,7 @@ Query.prototype.count = function (criteria, callback) { var conds = this._conditions , options = this._optionsForExec() - debug('count', this._collection.collection.name, conds, options); + debug('count', this._collection.collectionName, conds, options); callback = this._wrapCallback('count', callback, { conditions: conds , options: options @@ -1811,7 +1906,7 @@ Query.prototype.distinct = function (criteria, field, callback) { var conds = this._conditions , options = this._optionsForExec() - debug('distinct', this._collection.collection.name, conds, options); + debug('distinct', this._collection.collectionName, conds, options); callback = this._wrapCallback('distinct', callback, { conditions: conds , options: options @@ -1965,7 +2060,7 @@ Query.prototype.update = function update (criteria, doc, options, callback) { var criteria = this._conditions; doc = this._updateForExec(); - debug('update', this._collection.collection.name, criteria, doc, options); + debug('update', this._collection.collectionName, criteria, doc, options); callback = this._wrapCallback('update', callback, { conditions: criteria , doc: doc @@ -2032,7 +2127,7 @@ Query.prototype.remove = function (criteria, callback) { var conds = this._conditions; - debug('remove', this._collection.collection.name, conds, options); + debug('remove', this._collection.collectionName, conds, options); callback = this._wrapCallback('remove', callback, { conditions: conds , options: options @@ -2210,7 +2305,7 @@ Query.prototype._findAndModify = function (type, callback) { var conds = this._conditions; - debug('findAndModify', this._collection.collection.name, conds, doc, opts); + debug('findAndModify', this._collection.collectionName, conds, doc, opts); callback = this._wrapCallback('findAndModify', callback, { conditions: conds , doc: doc @@ -2312,7 +2407,19 @@ Query.prototype.exec = function exec (op, callback) { callback || (callback = true); } - this[this.op](callback); + var self = this; + + if ('function' == typeof callback) { + this[this.op](callback); + } else { + return new Query.Promise(function(success, error) { + self[self.op](function(err, val) { + if (err) error(err); + else success(val); + self = success = error = null; + }); + }); + } } /** @@ -2346,9 +2453,9 @@ Query.prototype.then = function(resolve, reject) { var self = this; var promise = new Query.Promise(function(success, error) { self.exec(function(err, val) { - self = resolve = reject = null; - if (err) return error(err); - success(val); + if (err) error(err); + else success(val); + self = success = error = null; }); }); return promise.then(resolve, reject); @@ -2370,7 +2477,7 @@ Query.prototype.stream = function(streamOptions) { var options = this._optionsForExec() options.fields = this._fieldsForExec() - debug('stream', this._collection.collection.name, conds, options, streamOptions); + debug('stream', this._collection.collectionName, conds, options, streamOptions); return this._collection.findStream(conds, options, streamOptions); } @@ -2406,6 +2513,11 @@ Query.prototype.selectedInclusively = function selectedInclusively () { for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (0 === this._fields[key]) return false; + if (this._fields[key] && + typeof this._fields[key] === 'object' && + this._fields[key].$meta) { + return false; + } } return true; @@ -2473,7 +2585,7 @@ Query.prototype._optionsForExec = function () { */ Query.prototype._fieldsForExec = function () { - return utils.clone(this._fields); + return utils.clone(this._fields, { retainKeyOrder: true }); } /** @@ -2519,6 +2631,7 @@ Query.prototype._updateForExec = function () { } } + this._compiledUpdate = ret; return ret; } @@ -2605,4 +2718,3 @@ module.exports = exports = Query; // TODO // test utils - diff --git a/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/node_modules/mquery/lib/permissions.js similarity index 96% rename from node_modules/mongoose/node_modules/mquery/lib/permissions.js rename to node_modules/mquery/lib/permissions.js index 07351d3..d46f7ae 100644 --- a/node_modules/mongoose/node_modules/mquery/lib/permissions.js +++ b/node_modules/mquery/lib/permissions.js @@ -80,12 +80,9 @@ denied.count = function (self) { return err; } -denied.count.select = denied.count.slice = -denied.count.sort = denied.count.batchSize = denied.count.comment = denied.count.maxScan = denied.count.snapshot = -denied.count.hint = denied.count.tailable = true; diff --git a/node_modules/mongoose/node_modules/mquery/lib/utils.js b/node_modules/mquery/lib/utils.js similarity index 97% rename from node_modules/mongoose/node_modules/mquery/lib/utils.js rename to node_modules/mquery/lib/utils.js index 6707ce2..f0337b6 100644 --- a/node_modules/mongoose/node_modules/mquery/lib/utils.js +++ b/node_modules/mquery/lib/utils.js @@ -329,3 +329,14 @@ exports.cloneBuffer = function (buff) { buff.copy(dupe, 0, 0, buff.length); return dupe; }; + +/** + * Check if this object is an arguments object + * + * @param {Any} v + * @return {Boolean} + */ + +exports.isArgumentsObject = function(v) { + return Object.prototype.toString.call(v) === '[object Arguments]'; +}; diff --git a/node_modules/mquery/package.json b/node_modules/mquery/package.json new file mode 100644 index 0000000..f64ced6 --- /dev/null +++ b/node_modules/mquery/package.json @@ -0,0 +1,63 @@ +{ + "_from": "mquery@1.10.0", + "_id": "mquery@1.10.0", + "_inBundle": false, + "_integrity": "sha1-hgPwKwtSTResBTmoWZYSTuF7fLM=", + "_location": "/mquery", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mquery@1.10.0", + "name": "mquery", + "escapedName": "mquery", + "rawSpec": "1.10.0", + "saveSpec": null, + "fetchSpec": "1.10.0" + }, + "_requiredBy": [ + "/mongoose" + ], + "_resolved": "https://registry.npmjs.org/mquery/-/mquery-1.10.0.tgz", + "_shasum": "8603f02b0b524d17ac0539a85996124ee17b7cb3", + "_spec": "mquery@1.10.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "bugs": { + "url": "https://github.com/aheckmann/mquery/issues/new" + }, + "bundleDependencies": false, + "dependencies": { + "bluebird": "2.10.2", + "debug": "2.2.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + }, + "deprecated": false, + "description": "Expressive query building for MongoDB", + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "1.9.x", + "mongodb": "1.4.38" + }, + "homepage": "https://github.com/aheckmann/mquery/", + "keywords": [ + "mongodb", + "query", + "builder" + ], + "license": "MIT", + "main": "lib/mquery.js", + "name": "mquery", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/mquery.git" + }, + "scripts": { + "test": "mocha test/index.js test/*.test.js" + }, + "version": "1.10.0" +} diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/node_modules/mquery/test/collection/browser.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/test/collection/browser.js rename to node_modules/mquery/test/collection/browser.js diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/node_modules/mquery/test/collection/mongo.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/test/collection/mongo.js rename to node_modules/mquery/test/collection/mongo.js diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/node_modules/mquery/test/collection/node.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/test/collection/node.js rename to node_modules/mquery/test/collection/node.js diff --git a/node_modules/mongoose/node_modules/mquery/test/env.js b/node_modules/mquery/test/env.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/test/env.js rename to node_modules/mquery/test/env.js diff --git a/node_modules/mongoose/node_modules/mquery/test/index.js b/node_modules/mquery/test/index.js similarity index 98% rename from node_modules/mongoose/node_modules/mquery/test/index.js rename to node_modules/mquery/test/index.js index 1b8025e..ccdc742 100644 --- a/node_modules/mongoose/node_modules/mquery/test/index.js +++ b/node_modules/mquery/test/index.js @@ -175,7 +175,6 @@ describe('mquery', function(){ assert.equal(m, n); }) }) - describe('equals', function(){ it('must be called after where()', function(){ var m = mquery(); @@ -194,7 +193,13 @@ describe('mquery', function(){ assert.equal(m, n); }) }) - + describe('eq', function(){ + it('is alias of equals', function(){ + var m = mquery(); + m.where('age').eq(1000); + assert.deepEqual({ age: 1000 }, m._conditions); + }) + }) describe('or', function(){ it('pushes onto the internal $or condition', function(){ var m = mquery(); @@ -945,7 +950,7 @@ describe('mquery', function(){ }, /Invalid select\(\) argument/); }) - it('accepts aguments objects', function(){ + it('accepts arguments objects', function(){ var m = mquery(); function t () { m.select(arguments); @@ -955,7 +960,6 @@ describe('mquery', function(){ }) noDistinct('select'); - no('count', 'select'); }) describe('selected', function() { @@ -990,6 +994,10 @@ describe('mquery', function(){ assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); done(); }); + it('when using $meta', function(done) { + assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); + done(); + }); }); describe('returns true', function() { @@ -1108,7 +1116,7 @@ describe('mquery', function(){ var m = mquery(); assert.equal(m.options.sort, undefined); }) - }) + }); it('works', function(){ var query = mquery(); @@ -1121,13 +1129,6 @@ describe('mquery', function(){ query = mquery(); var e= undefined; - try { - query.sort(['a', 1]); - } catch (err) { - e= err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); e= undefined; try { @@ -1136,16 +1137,30 @@ describe('mquery', function(){ e= err; } assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); - }) + assert.equal(e.message, 'Invalid sort() argument. Must be a string, object, or array.'); + }); it('handles $meta sort options', function(){ var query = mquery(); query.sort({ score: { $meta : "textScore" } }); assert.deepEqual(query.options.sort, { score : { $meta : "textScore" } }); - }) + }); - no('count', 'sort'); + it('array syntax', function(){ + var query = mquery(); + query.sort([['field', 1], ['test', -1]]); + assert.deepEqual(query.options.sort, [['field', 1], ['test', -1]]); + }); + + it('throws with mixed array/object syntax', function(){ + var query = mquery(); + assert.throws(function() { + query.sort({ field: 1 }).sort([['test', -1]]); + }, /Can't mix sort syntaxes/); + assert.throws(function() { + query.sort([['field', 1]]).sort({ test: 1 }); + }, /Can't mix sort syntaxes/); + }); }) function simpleOption (type, options) { @@ -1231,7 +1246,6 @@ describe('mquery', function(){ }) noDistinct('hint'); - no('count', 'hint'); }) describe('slaveOk', function(){ @@ -1556,9 +1570,9 @@ describe('mquery', function(){ describe('validates its option', function(){ it('sort', function(done){ - assert.throws(function(){ + assert.doesNotThrow(function(){ var m = mquery().sort('x').count(); - }, /sort cannot be used with count/); + }); done(); }) @@ -1618,13 +1632,6 @@ describe('mquery', function(){ done(); }) - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 }).count(); - }, /hint cannot be used with count/); - done(); - }) - it('tailable', function(done){ assert.throws(function(){ var m = mquery().tailable().count(); @@ -1962,7 +1969,7 @@ describe('mquery', function(){ m._collection.update = function (conds, doc, opts, cb) { m._collection.update = update; - assert.ok(!opts.safe); + assert.ok(opts.safe); assert.ok(true === opts.multi); assert.equal('forced', doc.$set.name); done(); @@ -2726,6 +2733,19 @@ describe('mquery', function(){ }, done); }); + it('supports exec() cb being called synchronously #66', function(done) { + var query = mquery(col).count({ name: 'then' }); + query.exec = function(cb) { + cb(null, 66); + } + + query.then(success, done); + function success(count){ + assert.equal(66, count); + done(); + } + }); + it('supports other Promise libs', function(done) { var bluebird = mquery.Promise; diff --git a/node_modules/mongoose/node_modules/mquery/test/utils.test.js b/node_modules/mquery/test/utils.test.js similarity index 100% rename from node_modules/mongoose/node_modules/mquery/test/utils.test.js rename to node_modules/mquery/test/utils.test.js diff --git a/node_modules/mongoose/node_modules/ms/.npmignore b/node_modules/ms/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/ms/.npmignore rename to node_modules/ms/.npmignore diff --git a/node_modules/mongoose/node_modules/ms/Makefile b/node_modules/ms/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/ms/Makefile rename to node_modules/ms/Makefile diff --git a/node_modules/mongoose/node_modules/ms/README.md b/node_modules/ms/README.md similarity index 100% rename from node_modules/mongoose/node_modules/ms/README.md rename to node_modules/ms/README.md diff --git a/node_modules/mongoose/node_modules/ms/ms.js b/node_modules/ms/ms.js similarity index 100% rename from node_modules/mongoose/node_modules/ms/ms.js rename to node_modules/ms/ms.js diff --git a/node_modules/mongoose/node_modules/ms/package.json b/node_modules/ms/package.json similarity index 54% rename from node_modules/mongoose/node_modules/ms/package.json rename to node_modules/ms/package.json index 1341788..ac1134e 100644 --- a/node_modules/mongoose/node_modules/ms/package.json +++ b/node_modules/ms/package.json @@ -1,38 +1,59 @@ { - "name": "ms", - "version": "0.1.0", - "description": "Tiny ms conversion utility", - "main": "./ms", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" - }, + "_defaultsLoaded": true, + "_engineSupported": true, + "_from": "ms@0.1.0", + "_id": "ms@0.1.0", + "_inBundle": false, + "_integrity": "sha1-8h+sSQ2vHXZn/RgP6QdzicyUQrI=", + "_location": "/ms", + "_nodeVersion": "v0.4.12", "_npmUser": { "name": "rauchg", "email": "rauchg@gmail.com" }, - "_id": "ms@0.1.0", + "_npmVersion": "1.0.106", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.1.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.1.0", + "saveSpec": null, + "fetchSpec": "0.1.0" + }, + "_requiredBy": [ + "/mongoose" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.1.0.tgz", + "_shasum": "f21fac490daf1d7667fd180fe9077389cc9442b2", + "_spec": "ms@0.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", + "bundleDependencies": false, "dependencies": {}, - "engines": { - "node": "*" + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" }, - "_engineSupported": true, - "_npmVersion": "1.0.106", - "_nodeVersion": "v0.4.12", - "_defaultsLoaded": true, + "directories": {}, "dist": { "shasum": "f21fac490daf1d7667fd180fe9077389cc9442b2", "tarball": "http://registry.npmjs.org/ms/-/ms-0.1.0.tgz" }, + "engines": { + "node": "*" + }, + "main": "./ms", "maintainers": [ { "name": "rauchg", "email": "rauchg@gmail.com" } ], - "directories": {}, - "_shasum": "f21fac490daf1d7667fd180fe9077389cc9442b2", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.1.0.tgz", - "_from": "ms@0.1.0" + "name": "ms", + "version": "0.1.0" } diff --git a/node_modules/mongoose/node_modules/ms/test/index.html b/node_modules/ms/test/index.html similarity index 100% rename from node_modules/mongoose/node_modules/ms/test/index.html rename to node_modules/ms/test/index.html diff --git a/node_modules/mongoose/node_modules/ms/test/support/jquery.js b/node_modules/ms/test/support/jquery.js similarity index 100% rename from node_modules/mongoose/node_modules/ms/test/support/jquery.js rename to node_modules/ms/test/support/jquery.js diff --git a/node_modules/mongoose/node_modules/ms/test/test.js b/node_modules/ms/test/test.js similarity index 100% rename from node_modules/mongoose/node_modules/ms/test/test.js rename to node_modules/ms/test/test.js diff --git a/node_modules/mongoose/node_modules/muri/.npmignore b/node_modules/muri/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/muri/.npmignore rename to node_modules/muri/.npmignore diff --git a/node_modules/mongoose/node_modules/muri/.travis.yml b/node_modules/muri/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/muri/.travis.yml rename to node_modules/muri/.travis.yml diff --git a/node_modules/mongoose/node_modules/muri/History.md b/node_modules/muri/History.md similarity index 100% rename from node_modules/mongoose/node_modules/muri/History.md rename to node_modules/muri/History.md diff --git a/node_modules/mongoose/node_modules/muri/LICENSE b/node_modules/muri/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/muri/LICENSE rename to node_modules/muri/LICENSE diff --git a/node_modules/mongoose/node_modules/muri/Makefile b/node_modules/muri/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/muri/Makefile rename to node_modules/muri/Makefile diff --git a/node_modules/mongoose/node_modules/muri/README.md b/node_modules/muri/README.md similarity index 100% rename from node_modules/mongoose/node_modules/muri/README.md rename to node_modules/muri/README.md diff --git a/node_modules/mongoose/node_modules/muri/index.js b/node_modules/muri/index.js similarity index 100% rename from node_modules/mongoose/node_modules/muri/index.js rename to node_modules/muri/index.js diff --git a/node_modules/mongoose/node_modules/muri/lib/index.js b/node_modules/muri/lib/index.js similarity index 100% rename from node_modules/mongoose/node_modules/muri/lib/index.js rename to node_modules/muri/lib/index.js diff --git a/node_modules/mongoose/node_modules/muri/package.json b/node_modules/muri/package.json similarity index 69% rename from node_modules/mongoose/node_modules/muri/package.json rename to node_modules/muri/package.json index 32a9e43..10ef868 100644 --- a/node_modules/mongoose/node_modules/muri/package.json +++ b/node_modules/muri/package.json @@ -1,42 +1,60 @@ { - "name": "muri", - "version": "1.1.0", - "description": "MongoDB URI parser", - "main": "index.js", - "scripts": { - "test": "make test" + "_from": "muri@1.1.0", + "_id": "muri@1.1.0", + "_inBundle": false, + "_integrity": "sha1-o6bXTmiogPQzokmnSWnLtmXMCt0=", + "_location": "/muri", + "_nodeVersion": "0.12.0", + "_npmUser": { + "name": "vkarpov15", + "email": "valkar207@gmail.com" }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/muri.git" + "_npmVersion": "2.5.1", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "muri@1.1.0", + "name": "muri", + "escapedName": "muri", + "rawSpec": "1.1.0", + "saveSpec": null, + "fetchSpec": "1.1.0" }, - "keywords": [ - "mongodb", - "uri", - "parser" + "_requiredBy": [ + "/mongoose" ], + "_resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz", + "_shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "_spec": "muri@1.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", "author": { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - "license": "MIT", + "bugs": { + "url": "https://github.com/aheckmann/muri/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "MongoDB URI parser", "devDependencies": { "mocha": "1.21.5" }, - "gitHead": "8f373948ef317865044994aaa98a013e769b2952", - "bugs": { - "url": "https://github.com/aheckmann/muri/issues" + "directories": {}, + "dist": { + "shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", + "tarball": "http://registry.npmjs.org/muri/-/muri-1.1.0.tgz" }, + "gitHead": "8f373948ef317865044994aaa98a013e769b2952", "homepage": "https://github.com/aheckmann/muri", - "_id": "muri@1.1.0", - "_shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", - "_from": "muri@1.1.0", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.0", - "_npmUser": { - "name": "vkarpov15", - "email": "valkar207@gmail.com" - }, + "keywords": [ + "mongodb", + "uri", + "parser" + ], + "license": "MIT", + "main": "index.js", "maintainers": [ { "name": "aaron", @@ -47,10 +65,13 @@ "email": "val@karpov.io" } ], - "dist": { - "shasum": "a3a6d74e68a880f433a249a74969cbb665cc0add", - "tarball": "http://registry.npmjs.org/muri/-/muri-1.1.0.tgz" + "name": "muri", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/muri.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz" + "scripts": { + "test": "make test" + }, + "version": "1.1.0" } diff --git a/node_modules/mongoose/node_modules/muri/test/index.js b/node_modules/muri/test/index.js similarity index 100% rename from node_modules/mongoose/node_modules/muri/test/index.js rename to node_modules/muri/test/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/.dntrc b/node_modules/nan/.dntrc similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/.dntrc rename to node_modules/nan/.dntrc diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md b/node_modules/nan/CHANGELOG.md similarity index 93% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md rename to node_modules/nan/CHANGELOG.md index 26e859d..8e8f052 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/CHANGELOG.md +++ b/node_modules/nan/CHANGELOG.md @@ -1,6 +1,30 @@ # NAN ChangeLog -**Version 1.7.0: current Node 12: 0.12.0, Node 10: 0.10.36, io.js: 1.4.1** +**Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1** + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 ### 1.7.0 Feb 28 2015 diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/LICENSE.md b/node_modules/nan/LICENSE.md similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/LICENSE.md rename to node_modules/nan/LICENSE.md diff --git a/node_modules/nan/README.md b/node_modules/nan/README.md new file mode 100644 index 0000000..26f6947 --- /dev/null +++ b/node_modules/nan/README.md @@ -0,0 +1,1402 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** + +***Current version: 1.8.4*** + +*(See [CHANGELOG.md](https://github.com/iojs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) + +[![Build Status](https://api.travis-ci.org/iojs/nan.svg?branch=master)](http://travis-ci.org/iojs/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Porting](#porting)** + * **[Governance & Contributing](#governance)** + + +## News & Updates + +### Apr-2015: 1.8.0 release + +* Support V8 4.2 +* Removed support for creating `Signature`s with arguments +* Backported thread local storage routines for libuv + +### Feb-2015: 1.7.0 release + +* Made `NanCallback::Call` accept optional target +* Support atom-shell 0.21 + +Node 0.12.0 is out and supported by NAN. So is atom-shell 0.21. `NanCallback::Call` now accepts an optional `target` argument like `NanMakeCallback`. + +### Jan-2015: 1.6.0 release + +* Deprecated `NanNewContextHandle` in favor of `NanNew` +* Added `NanSetCounterFunction`, `NanSetCreateHistogramFunction`, `NanSetAddHistogramSampleFunction` +* Added `NanIdleNotification`, `NanLowMemoryNotification`, `NanContextDisposedNotification` +* Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` + +### Jan-2015: 1.5.0 release + +* Support [io.js](https://github.com/iojs/io.js) thanks to [Ben Noordhuis](bnoordhuis) +* Rewritten NanNew internals thanks to [David Siegel](agnat) +* NanAsyncWorker now supports progress reporting thanks to [Brett Lawson](brett19) + +### Aug-2014: 1.3.0 release + +* `NanCString()` and `NanRawString()` have been deprecated in favour of new NanAsciiString, NanUtf8String and NanUcs2String. These classes manage the underlying memory for you in a safer way than just handing off an allocated array. You should now `*NanAsciiString(handle)` to access the raw `char` data, you can also allocate on the heap if you need to keep a reference. +* Two more NanMakeCallback overloads have been added to for parity with Node core. +* You can now `NanNew(std::string)` (use `NanNew(std::string&)` to pass by reference) +* NanSetTemplate, NanSetPrototypeTemplate and NanSetInstanceTemplate have been added. + +### May-2014: 1.1.0 release + +* We've deprecated `NanSymbol()`, you should just use `NanNew()` now. +* `NanNull()`, `NanUndefined()`, `NanTrue()`, `NanFalse()` all return `Local`s now. +* `nan_isolate` is gone, it was intended to be internal-only but if you were using it then you should switch to `v8::Isolate::GetCurrent()`. +* `NanNew()` has received some additional overload-love so you should be able to give it many kinds of values without specifying the ``. +* Lots of small fixes and additions to expand the V8 API coverage, *use the source, Luke*. + + +### May-2014: Major changes for V8 3.25 / Node 0.11.13 + +Node 0.11.11 and 0.11.12 were both broken releases for native add-ons, you simply can't properly compile against either of them for different reasons. But we now have a 0.11.13 release that jumps a couple of versions of V8 ahead and includes some more, major (traumatic) API changes. + +Because we are now nearing Node 0.12 and estimate that the version of V8 we are using in Node 0.11.13 will be close to the API we get for 0.12, we have taken the opportunity to not only *fix* NAN for 0.11.13 but make some major changes to improve the NAN API. + +We have **removed support for Node 0.11 versions prior to 0.11.13**. As usual, our tests are run against (and pass) the last 5 versions of Node 0.8 and Node 0.10. We also include Node 0.11.13 obviously. + +The major change is something that [Benjamin Byholm](kkoopa) has put many hours in to. We now have a fantastic new `NanNew(args)` interface for creating new `Local`s, this replaces `NanNewLocal()` and much more. If you look in [./nan.h](nan.h) you'll see a large number of overloaded versions of this method. In general you should be able to `NanNew(arguments)` for any type you want to make a `Local` from. This includes `Persistent` types, so we now have a `Local NanNew(const Persistent arg)` to replace `NanPersistentToLocal()`. + +We also now have `NanUndefined()`, `NanNull()`, `NanTrue()` and `NanFalse()`. Mainly because of the new requirement for an `Isolate` argument for each of the native V8 versions of this. + +V8 has now introduced an `EscapableHandleScope` from which you `scope.Escape(Local value)` to *return* a value from a one scope to another. This replaces the standard `HandleScope` and `scope.Close(Local value)`, although `HandleScope` still exists for when you don't need to return a handle to the caller. For NAN we are exposing it as `NanEscapableScope()` and `NanEscapeScope()`, while `NanScope()` is still how you create a new scope that doesn't need to return handles. For older versions of Node/V8, it'll still map to the older `HandleScope` functionality. + +`NanFromV8String()` was deprecated and has now been removed. You should use `NanCString()` or `NanRawString()` instead. + +Because `node::MakeCallback()` now takes an `Isolate`, and because it doesn't exist in older versions of Node, we've introduced `NanMakeCallback()`. You should *always* use this when calling a JavaScript function from C++. + +There's lots more, check out the Changelog in nan.h or look through [#86](https://github.com/iojs/nan/pull/86) for all the gory details. + +### Dec-2013: NanCString and NanRawString + +Two new functions have been introduced to replace the functionality that's been provided by `NanFromV8String` until now. NanCString has sensible defaults so it's super easy to fetch a null-terminated c-style string out of a `v8::String`. `NanFromV8String` is still around and has defaults that allow you to pass a single handle to fetch a `char*` while `NanRawString` requires a little more attention to arguments. + +### Nov-2013: Node 0.11.9+ breaking V8 change + +The version of V8 that's shipping with Node 0.11.9+ has changed the signature for new `Local`s to: `v8::Local::New(isolate, value)`, i.e. introducing the `isolate` argument and therefore breaking all new `Local` declarations for previous versions. NAN 0.6+ now includes a `NanNewLocal(value)` that can be used in place to work around this incompatibility and maintain compatibility with 0.8->0.11.9+ (minus a few early 0.11 releases). + +For example, if you wanted to return a `null` on a callback you will have to change the argument from `v8::Local::New(v8::Null())` to `NanNewLocal(v8::Null())`. + +### Nov-2013: Change to binding.gyp `"include_dirs"` for NAN + +Inclusion of NAN in a project's binding.gyp is now greatly simplified. You can now just use `" +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use. + +For a simpler example, see the **[async pi estimation example](https://github.com/iojs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + +Compare to the current 0.10 version of this example, found in the [node-addon-examples](https://github.com/iojs/node-addon-examples/tree/master/9_async_work) repository and also a 0.11 version of the same found [here](https://github.com/kkoopa/node-addon-examples/tree/5c01f58fc993377a567812597e54a83af69686d7/9_async_work). + +Note that there is no embedded version sniffing going on here and also the async work is made much simpler, see below for details on the `NanAsyncWorker` class. + +```c++ +// addon.cc +#include +#include +// ... + +using v8::FunctionTemplate; +using v8::Handle; +using v8::Object; +using v8::String; + +void InitAll(Handle exports) { + exports->Set(NanNew("calculateSync"), + NanNew(CalculateSync)->GetFunction()); + + exports->Set(NanNew("calculateAsync"), + NanNew(CalculateAsync)->GetFunction()); +} + +NODE_MODULE(addon, InitAll) +``` + +```c++ +// sync.h +#include +#include + +NAN_METHOD(CalculateSync); +``` + +```c++ +// sync.cc +#include +#include +#include "./sync.h" +// ... + +using v8::Number; + +// Simple synchronous access to the `Estimate()` function +NAN_METHOD(CalculateSync) { + NanScope(); + + // expect a number as the first argument + int points = args[0]->Uint32Value(); + double est = Estimate(points); + + NanReturnValue(NanNew(est)); +} +``` + +```c++ +// async.h +#include +#include + +NAN_METHOD(CalculateAsync); +``` + +```c++ +// async.cc +#include +#include +#include "./async.h" + +// ... + +using v8::Function; +using v8::Local; +using v8::Null; +using v8::Number; +using v8::Value; + +class PiWorker : public NanAsyncWorker { + public: + PiWorker(NanCallback *callback, int points) + : NanAsyncWorker(callback), points(points) {} + ~PiWorker() {} + + // Executed inside the worker-thread. + // It is not safe to access V8, or V8 data structures + // here, so everything we need for input and output + // should go on `this`. + void Execute () { + estimate = Estimate(points); + } + + // Executed when the async work is complete + // this function will be run inside the main event loop + // so it is safe to use V8 again + void HandleOKCallback () { + NanScope(); + + Local argv[] = { + NanNull() + , NanNew(estimate) + }; + + callback->Call(2, argv); + }; + + private: + int points; + double estimate; +}; + +// Asynchronous access to the `Estimate()` function +NAN_METHOD(CalculateAsync) { + NanScope(); + + int points = args[0]->Uint32Value(); + NanCallback *callback = new NanCallback(args[1].As()); + + NanAsyncQueueWorker(new PiWorker(callback, points)); + NanReturnUndefined(); +} +``` + + +## API + + * NAN_METHOD + * NAN_GETTER + * NAN_SETTER + * NAN_PROPERTY_GETTER + * NAN_PROPERTY_SETTER + * NAN_PROPERTY_ENUMERATOR + * NAN_PROPERTY_DELETER + * NAN_PROPERTY_QUERY + * NAN_INDEX_GETTER + * NAN_INDEX_SETTER + * NAN_INDEX_ENUMERATOR + * NAN_INDEX_DELETER + * NAN_INDEX_QUERY + * NAN_GC_CALLBACK + * NAN_WEAK_CALLBACK + * NAN_DEPRECATED + * NAN_INLINE + * NanNew + * NanUndefined + * NanNull + * NanTrue + * NanFalse + * NanReturnValue + * NanReturnUndefined + * NanReturnNull + * NanReturnEmptyString + * NanReturnThis + * NanReturnHolder + * NanScope + * NanEscapableScope + * NanEscapeScope + * NanLocker + * NanUnlocker + * NanGetInternalFieldPointer + * NanSetInternalFieldPointer + * NanObjectWrapHandle + * NanSymbol + * NanGetPointerSafe + * NanSetPointerSafe + * NanRawString + * NanCString + * NanAsciiString + * NanUtf8String + * NanUcs2String + * NanBooleanOptionValue + * NanUInt32OptionValue + * NanError, NanTypeError, NanRangeError + * NanThrowError, NanThrowTypeError, NanThrowRangeError, NanThrowError(Handle), NanThrowError(Handle, int) + * NanNewBufferHandle(char *, size_t, FreeCallback, void *), NanNewBufferHandle(char *, uint32_t), NanNewBufferHandle(uint32_t) + * NanBufferUse(char *, uint32_t) + * NanNewContextHandle + * NanGetCurrentContext + * NanHasInstance + * NanDisposePersistent + * NanAssignPersistent + * NanMakeWeakPersistent + * NanSetTemplate + * NanSetPrototypeTemplate + * NanSetInstanceTemplate + * NanMakeCallback + * NanEncode + * NanDecodeBytes + * NanDecodeWrite + * NanCompileScript + * NanRunScript + * NanAdjustExternalMemory + * NanAddGCEpilogueCallback + * NanAddGCPrologueCallback + * NanRemoveGCEpilogueCallback + * NanRemoveGCPrologueCallback + * NanGetHeapStatistics + * NanSetCounterFunction + * NanSetCreateHistogramFunction + * NanSetAddHistogramSampleFunction + * NanIdleNotification + * NanLowMemoryNotification + * NanContextDisposedNotification + * NanCallback + * NanAsyncWorker + * NanAsyncQueueWorker + + +### NAN_METHOD(methodname) + +Use `NAN_METHOD` to define your V8 accessible methods: + +```c++ +// .h: +class Foo : public node::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +The reason for this macro is because of the method signature change in 0.11: + +```c++ +// 0.10 and below: +Handle name(const Arguments& args) + +// 0.11 and above +void name(const FunctionCallbackInfo& args) +``` + +The introduction of `FunctionCallbackInfo` brings additional complications: + + +### NAN_GETTER(methodname) + +Use `NAN_GETTER` to declare your V8 accessible getters. You get a `Local` `property` and an appropriately typed `args` object that can act like the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`. + + +### NAN_SETTER(methodname) + +Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_GETTER(cbname) +Use `NAN_PROPERTY_GETTER` to declare your V8 accessible property getters. You get a `Local` `property` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`. + + +### NAN_PROPERTY_SETTER(cbname) +Use `NAN_PROPERTY_SETTER` to declare your V8 accessible property setters. Same as `NAN_PROPERTY_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_ENUMERATOR(cbname) +Use `NAN_PROPERTY_ENUMERATOR` to declare your V8 accessible property enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_PROPERTY_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`. + + +### NAN_PROPERTY_DELETER(cbname) +Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`. + + +### NAN_PROPERTY_QUERY(cbname) +Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`. + + +### NAN_INDEX_GETTER(cbname) +Use `NAN_INDEX_GETTER` to declare your V8 accessible index getters. You get a `uint32_t` `index` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_GETTER`. + + +### NAN_INDEX_SETTER(cbname) +Use `NAN_INDEX_SETTER` to declare your V8 accessible index setters. Same as `NAN_INDEX_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_INDEX_ENUMERATOR(cbname) +Use `NAN_INDEX_ENUMERATOR` to declare your V8 accessible index enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_INDEX_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_ENUMERATOR`. + + +### NAN_INDEX_DELETER(cbname) +Use `NAN_INDEX_DELETER` to declare your V8 accessible index deleters. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_DELETER`. + + +### NAN_INDEX_QUERY(cbname) +Use `NAN_INDEX_QUERY` to declare your V8 accessible index queries. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_QUERY`. + + +### NAN_GC_CALLBACK(cbname) +Use `NAN_GC_CALLBACK` to declare your callbacks for `NanAddGCEpilogueCallback` and `NanAddGCPrologueCallback`. You get arguments `GCType type` and `GCCallbackFlags flags`. + +```c++ +static Persistent callback; + +NAN_GC_CALLBACK(gcPrologueCallback) { + Local argv[] = {NanNew("prologue")}; + NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv); +} + +NAN_METHOD(Hook) { + NanScope(); + NanAssignPersistent(callback, args[0].As()); + NanAddGCPrologueCallback(gcPrologueCallback); + NanReturnValue(args.Holder()); +} +``` + + +### NAN_WEAK_CALLBACK(cbname) + +Use `NAN_WEAK_CALLBACK` to define your V8 WeakReference callbacks. There is an argument object `const _NanWeakCallbackData &data` allowing access to the weak object and the supplied parameter through its `GetValue` and `GetParameter` methods. You can even access the weak callback info object through the `GetCallbackInfo()`method, but you probably should not. `Revive()` keeps the weak object alive until the next GC round. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + int *parameter = data.GetParameter(); + NanMakeCallback(NanGetCurrentContext()->Global(), data.GetValue(), 0, NULL); + if ((*parameter)++ == 0) { + data.Revive(); + } else { + delete parameter; + } +} +``` + + +### NAN_DEPRECATED +Declares a function as deprecated. + +```c++ +static NAN_DEPRECATED NAN_METHOD(foo) { + ... +} +``` + + +### NAN_INLINE +Inlines a function. + +```c++ +NAN_INLINE int foo(int bar) { + ... +} +``` + + +### Local<T> NanNew<T>( ... ) + +Use `NanNew` to construct almost all v8 objects (bound `Script`s are constructed with `NanCompileScript(Handle)`) and make new local handles. + +```c++ +Local s = NanNew("value"); + +... + +Persistent o; + +... + +Local lo = NanNew(o); + +``` + + +### Local<Primitive> NanUndefined() + +Use instead of `Undefined()` + + +### Local<Primitive> NanNull() + +Use instead of `Null()` + + +### Local<Boolean> NanTrue() + +Use instead of `True()` + + +### Local<Boolean> NanFalse() + +Use instead of `False()` + + +### NanReturnValue(Handle<Value>) + +Use `NanReturnValue` when you want to return a value from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Bar) { + ... + + NanReturnValue(NanNew("FooBar!")); +} +``` + +No `return` statement required. + +For convenience, `NanReturnValue` also accepts common primitives directly by implicitly performing an overloaded `NanNew(T)`. + +```c++ +NanReturnValue("FooBar!"); +NanReturnValue(true); +NanReturnValue(12); +NanReturnValue(3.14); +``` + + +### NanReturnUndefined() + +Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnUndefined(); +} +``` + + +### NanReturnNull() + +Use `NanReturnNull` when you want to return `Null` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnNull(); +} +``` + + +### NanReturnEmptyString() + +Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnEmptyString(); +} +``` + + +### NanReturnThis() + +Use `NanReturnThis` when you want to return `This` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnThis(); +} +``` + + +### NanReturnHolder() + +Use `NanReturnHolder` when you want to return `Holder` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnHolder(); +} +``` + + +### NanScope() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope` when you do not wish to return handles (`Handle` or `Local`) to the surrounding scope (or in functions directly exposed to V8, as they do not return values in the normal sense): + +```c++ +NAN_METHOD(Foo::Bar) { + NanScope(); + + NanReturnValue(NanNew("FooBar!")); +} +``` + +This method is not directly exposed to V8, nor does it return a handle, so it uses an unescapable scope: + +```c++ +bool Foo::Bar() { + NanScope(); + + Local val = NanFalse(); + ... + return val->Value(); +} +``` + + +### NanEscapableScope() + +The separation of handle scopes into escapable and inescapable scopes makes `NanEscapableScope()` necessary, use it in place of `HandleScope scope` when you later wish to return a handle (`Handle` or `Local`) from the scope, this is for internal functions not directly exposed to V8: + +```c++ +Handle Foo::Bar() { + NanEscapableScope(); + + return NanEscapeScope(NanNew("FooBar!")); +} +``` + + +### Local<T> NanEscapeScope(Handle<T> value); +Use together with `NanEscapableScope` to escape the scope. Corresponds to `HandleScope::Close` or `EscapableHandleScope::Escape`. + + +### NanLocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### NanUnlocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### void * NanGetInternalFieldPointer(Handle<Object>, int) + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +```c++ +Local obj; +... +NanGetInternalFieldPointer(obj, 0); +``` + +### void NanSetInternalFieldPointer(Handle<Object>, int, void *) + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +```c++ +static Persistent dataWrapperCtor; +... +Local wrapper = NanNew(dataWrapperCtor)->NewInstance(); +NanSetInternalFieldPointer(wrapper, 0, this); +``` + + +### Local<Object> NanObjectWrapHandle(const node::ObjectWrap &obj) + +When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`: + +```c++ +NanObjectWrapHandle(iterator)->Get(NanNew("end")) +``` + + +### ~~Local<String> NanSymbol(const char *)~~ + +Deprecated. Use `NanNew` instead. +~~Use to create string symbol objects (i.e. `v8::String::NewSymbol(x)`), for getting and setting object properties, or names of objects.~~ + +```c++ +bool foo = false; +if (obj->Has(NanNew("foo"))) + foo = optionsObj->Get(NanNew("foo"))->BooleanValue() +``` + + +### Type NanGetPointerSafe(Type *[, Type]) + +A helper for getting values from optional pointers. If the pointer is `NULL`, the function returns the optional default value, which defaults to `0`. Otherwise, the function returns the value the pointer points to. + +```c++ +char *plugh(uint32_t *optional) { + char res[] = "xyzzy"; + uint32_t param = NanGetPointerSafe(optional, 0x1337); + switch (param) { + ... + } + NanSetPointerSafe(optional, 0xDEADBEEF); +} +``` + + +### bool NanSetPointerSafe(Type *, Type) + +A helper for setting optional argument pointers. If the pointer is `NULL`, the function simply returns `false`. Otherwise, the value is assigned to the variable the pointer points to. + +```c++ +const char *plugh(size_t *outputsize) { + char res[] = "xyzzy"; + if !(NanSetPointerSafe(outputsize, strlen(res) + 1)) { + ... + } + + ... +} +``` + + +### ~~void* NanRawString(Handle<Value>, enum Nan::Encoding, size_t *, void *, size_t, int)~~ + +Deprecated. Use something else. + +~~When you want to convert a V8 `String` to a `char*` buffer, use `NanRawString`. You have to supply an encoding as well as a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows setting `String::WriteOptions`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +void* decoded = NanRawString(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED); +... +delete[] reinterpret_cast(decoded); +``` + + +### ~~char* NanCString(Handle<Value>, size_t *[, char *, size_t, int])~~ + +Deprecated. Use `String::Utf8Value` or `NanUtf8String` instead. + +~~When you want to convert a V8 `String` to a null-terminated C `char*` use `NanCString`. The resulting `char*` will be UTF-8-encoded, and you need to supply a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows optionally setting `String::WriteOptions`, which default to `v8::String::NO_OPTIONS`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:~~ + +```c++ +size_t count; +char* name = NanCString(args[0], &count); +... +delete[] name; +``` + + +### NanAsciiString + +Contrary to the name, this is not actually an ASCII string, it is a one-byte string with no particular encoding. Do not use unless you actually need this incorrect legacy behavior. Consider fixing your broken code instead. If you actually have a proper ASCII-string, use UTF-8, which is a proper superset of ASCII. +Convert a `String` to zero-terminated, sort-of Ascii-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanAsciiString(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanAsciiString baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanAsciiString *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanAsciiString(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### NanUtf8String + +Equivalent to `String::Utf8Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Utf8-encoded `char *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUtf8String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUtf8String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUtf8String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUtf8String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + + +### NanUcs2String + +Equivalent to `String::Value`, it only exists for the sake of completeness. +Convert a `String` to zero-terminated, Ucs2-encoded `uint16_t *`. The underlying buffer is freed when the owner object goes out of scope, so make a copy or heap allocation if you need it to stick around. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUcs2String(arg[0]))); +} +``` + +####*WRONG*: +the buffer `str` points to has been freed when `baz` was destroyed: +```c++ +static char *str; + +NAN_METHOD(bar) { + NanScope(); + NanUcs2String baz(arg[0]); + + str = *baz; + NanReturnUndefined(); // baz goes out of scope, freeing str +} + +... + +printf(str); // use-after-free error +``` + +####*RIGHT*: +```c++ +static NanUcs2String *str; + +NAN_METHOD(bar) { + NanScope(); + str = new NanUcs2String(arg[0]); + NanReturnUndefined(); +} + +... + +printf(**str); +``` + + +### bool NanBooleanOptionValue(Handle<Value>, Handle<String>[, bool]) + +When you have an "options" object that you need to fetch properties from, boolean options can be fetched with this pair. They check first if the object exists (`IsEmpty`), then if the object has the given property (`Has`) then they get and convert/coerce the property to a `bool`. + +The optional last parameter is the *default* value, which is `false` if left off: + +```c++ +// `foo` is false unless the user supplies a truthy value for it +bool foo = NanBooleanOptionValue(optionsObj, NanNew("foo")); +// `bar` is true unless the user supplies a falsy value for it +bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanNew("bar"), true); +``` + + +### uint32_t NanUInt32OptionValue(Handle<Value>, Handle<String>, uint32_t) + +Similar to `NanBooleanOptionValue`, use `NanUInt32OptionValue` to fetch an integer option from your options object. Can be any kind of JavaScript `Number` and it will be coerced to an unsigned 32-bit integer. + +Requires all 3 arguments as a default is not optional: + +```c++ +uint32_t count = NanUInt32OptionValue(optionsObj, NanNew("count"), 1024); +``` + + +### NanError(message), NanTypeError(message), NanRangeError(message) + +For making `Error`, `TypeError` and `RangeError` objects. + +```c++ +Local res = NanError("you must supply a callback argument"); +``` + + +### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local<Value>), NanThrowError(Local<Value>, int) + +For throwing `Error`, `TypeError` and `RangeError` objects. + +```c++ +NanThrowError("you must supply a callback argument"); +``` + +Can also handle any custom object you may want to throw. If used with the error code argument, it will add the supplied error code to the error object as a property called `code`. + + +### Local<Object> NanNewBufferHandle(char *, uint32_t), Local<Object> NanNewBufferHandle(uint32_t) + +The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation: + +```c++ +NanNewBufferHandle((char*)value.data(), value.size()); +``` + +Can also be used to initialize a `Buffer` with just a `size` argument. + +Can also be supplied with a `NanFreeCallback` and a hint for the garbage collector. + + +### Local<Object> NanBufferUse(char*, uint32_t) + +`Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data. +While it was possible to get around this, it required a shim by passing a +callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove +needing to use this shim. + +`NanBufferUse` uses the `char*` passed as the backing data, and will free the +memory automatically when the weak callback is called. Keep this in mind, as +careless use can lead to "double free or corruption" and other cryptic failures. + + +### bool NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>) + +Can be used to check the type of an object to determine it is of a particular class you have already defined and have a `Persistent` handle for. + + +### ~~Local<Context> NanNewContextHandle([ExtensionConfiguration*, Handle<ObjectTemplate>, Handle<Value>])~~ + +Deprecated. Use `NanNew` instead. + +~~Creates a new `Local` handle.~~ + +```c++ +Local ftmpl = NanNew(); +Local otmpl = ftmpl->InstanceTemplate(); +Local ctx = NanNewContextHandle(NULL, otmpl); +``` + + +### Local<Context> NanGetCurrentContext() + +Gets the current context. + +```c++ +Local ctx = NanGetCurrentContext(); +``` + + +### void NanDisposePersistent(Persistent<T> &) + +Use `NanDisposePersistent` to dispose a `Persistent` handle. + +```c++ +NanDisposePersistent(persistentHandle); +``` + + +### NanAssignPersistent(handle, object) + +Use `NanAssignPersistent` to assign a non-`Persistent` handle to a `Persistent` one. You can no longer just declare a `Persistent` handle and assign directly to it later, you have to `Reset` it in Node 0.11, so this makes it easier. + +In general it is now better to place anything you want to protect from V8's garbage collector as properties of a generic `Object` and then assign that to a `Persistent`. This works in older versions of Node also if you use `NanAssignPersistent`: + +```c++ +Persistent persistentHandle; + +... + +Local obj = NanNew(); +obj->Set(NanNew("key"), keyHandle); // where keyHandle might be a Local +NanAssignPersistent(persistentHandle, obj) +``` + + +### _NanWeakCallbackInfo<T, P>* NanMakeWeakPersistent(Handle<T>, P*, _NanWeakCallbackInfo<T, P>::Callback) + +Creates a weak persistent handle with the supplied parameter and `NAN_WEAK_CALLBACK`. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + +... + +} + +Local func; + +... + +int *parameter = new int(0); +NanMakeWeakPersistent(func, parameter, &weakCallback); +``` + + +### NanSetTemplate(templ, name, value [, attributes]) + +Use to add properties on object and function templates. + + +### NanSetPrototypeTemplate(templ, name, value [, attributes]) + +Use to add prototype properties on function templates. + + +### NanSetInstanceTemplate(templ, name, value [, attributes]) + +Use to add instance properties on function templates. + + +### NanMakeCallback(target, func, argc, argv) + +Use instead of `node::MakeCallback` to call javascript functions. This (or `NanCallback`) is the only proper way of calling functions. You must _*never, ever*_ directly use `Function::Call`, it will lead to run-time failures. + + +### NanEncode(const void*, size_t[, enum Nan::Encoding]) + +Replaces `node::Encode`. + + +### NanDecodeBytes(v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeBytes`. + + +### NanDecodeWrite(char *, size_t, v8::Handle<v8::Value>[, enum Nan::Encoding]) + +Replaces `node::DecodeWrite`. + + +### NanCompileScript(Handle s [, const ScriptOrigin& origin]) + +Use to create new scripts bound to the current context. + + +### NanRunScript(script) + +Use to run both bound and unbound scripts. + + +### NanAdjustExternalMemory(int change_in_bytes) + +Simply does `AdjustAmountOfExternalAllocatedMemory`, note that the argument and returned value have type `int`. + + +### NanAddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCEpilogueCallback` + + +### NanAddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCPrologueCallback` + + +### NanRemoveGCEpilogueCallback(GCEpilogueCallback callback) + +Simply does `RemoveGCEpilogueCallback` + + +### NanRemoveGCPrologueCallback(GCPrologueCallback callback) + +Simply does `RemoveGCPrologueCallback` + + +### NanGetHeapStatistics(HeapStatistics *heap_statistics) + +Simply does `GetHeapStatistics` + + +### NanSetCounterFunction(CounterLookupCallback cb) + +Simply does `SetCounterFunction` + + +### NanSetCreateHistogramFunction(CreateHistogramCallback cb) + +Simply does `SetCreateHistogramFunction` + + +### NanSetAddHistogramSampleFunction(AddHistogramSampleCallback cb) + +Simply does `SetAddHistogramSampleFunction` + + +### NanIdleNotification(int idle_time_in_ms) + +Simply does `IdleNotification` + + +### NanLowMemoryNotification() + +Simply does `LowMemoryNotification` + + +### NanContextDisposedNotification() + +Simply does `ContextDisposedNotification` + + +### NanCallback + +Because of the difficulties imposed by the changes to `Persistent` handles in V8 in Node 0.11, creating `Persistent` versions of your `Handle` is annoyingly tricky. `NanCallback` makes it easier by taking your handle, making it persistent until the `NanCallback` is deleted and even providing a handy `Call()` method to fetch and execute the callback `Function`. + +```c++ +Local callbackHandle = args[0].As(); +NanCallback *callback = new NanCallback(callbackHandle); +// pass `callback` around and it's safe from GC until you: +delete callback; +``` + +You can execute the callback like so: + +```c++ +// no arguments: +callback->Call(0, NULL); + +// an error argument: +Handle argv[] = { + NanError(NanNew("fail!")) +}; +callback->Call(1, argv); + +// a success argument: +Handle argv[] = { + NanNull(), + NanNew("w00t!") +}; +callback->Call(2, argv); +``` + +`NanCallback` also has a `Local GetFunction()` method that you can use +to fetch a local handle to the underlying callback function, as well as a +`void SetFunction(Handle)` for setting the callback on the +`NanCallback`. You can check if a `NanCallback` is empty with the `bool IsEmpty()` method. Additionally a generic constructor is available for using +`NanCallback` without performing heap allocations. + + +### NanAsyncWorker + +`NanAsyncWorker` is an abstract class that you can subclass to have much of the annoying async queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the async work is in progress. + +See a rough outline of the implementation: + +```c++ +class NanAsyncWorker { +public: + NanAsyncWorker (NanCallback *callback); + + // Clean up persistent handles and delete the *callback + virtual ~NanAsyncWorker (); + + // Check the `ErrorMessage()` and call HandleOKCallback() + // or HandleErrorCallback depending on whether it has been set or not + virtual void WorkComplete (); + + // You must implement this to do some async work. If there is an + // error then use `SetErrorMessage()` to set an error message and the callback will + // be passed that string in an Error object + virtual void Execute (); + + // Save a V8 object in a Persistent handle to protect it from GC + void SaveToPersistent(const char *key, Local &obj); + + // Fetch a stored V8 object (don't call from within `Execute()`) + Local GetFromPersistent(const char *key); + + // Get the error message (or NULL) + const char *ErrorMessage(); + + // Set an error message + void SetErrorMessage(const char *msg); + +protected: + // Default implementation calls the callback function with no arguments. + // Override this to return meaningful data + virtual void HandleOKCallback (); + + // Default implementation calls the callback function with an Error object + // wrapping the `errmsg` string + virtual void HandleErrorCallback (); +}; +``` + + +### NanAsyncQueueWorker(NanAsyncWorker *) + +`NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you—most of the logic for this is embedded in `NanAsyncWorker`. + + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + +## Porting + +Follows is a guide to porting your C++ node to NAN. + +
The following features can be disabled
+ + + + + + + + + + + + + + + +
AspectWithout NANWith NAN
Function declaration
class MyClass : public ObjectWrap {
+    ....
+    static Handle ToString(const Arguments& args);
+    ....
+}
class MyClass : public ObjectWrap {
+    ....
+    static NAN_METHOD(ToString);
+    ....
+}
Function definition
Handle
+MyClass::ToString(const Arguments& args)
+{
+	HandleScope scope;
+	....
+}
+NAN_METHOD(MyClass::ToString)
+{
+  NanScope();
+  ....
+}
Return a value
return scope.Close(result);
NanReturnValue(result);
Return undefined
return Undefined();
NanReturnUndefined();
Throw an error
return ThrowException(
+  Exception::Error(
+    String::New("Error text...")));
return NanThrowError("Error text...");
New v8 string literal
String::NewSymbol("my text")
NanNew("my text")
+ +## Contributors + + + +## Governance & Contributing + +NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +### Developer's Certificate of Origin 1.0 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or +* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or +* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. + + +### WG Members / Collaborators + + + + + + + + + +
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnat-
+ +## Licence & copyright + +Copyright (c) 2015 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/appveyor.yml b/node_modules/nan/appveyor.yml similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/appveyor.yml rename to node_modules/nan/appveyor.yml diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/include_dirs.js b/node_modules/nan/include_dirs.js similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/include_dirs.js rename to node_modules/nan/include_dirs.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h b/node_modules/nan/nan.h similarity index 95% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h rename to node_modules/nan/nan.h index 23c38e4..fb025a9 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan.h +++ b/node_modules/nan/nan.h @@ -12,7 +12,7 @@ * * MIT License * - * Version 1.7.0: current Node 12: 0.12.0, Node 10: 0.10.36, io.js: 1.4.1 + * Version 1.8.4: current Node 12: 0.12.2, Node 10: 0.10.38, io.js: 1.8.1 * * See https://github.com/rvagg/nan for the latest update to this file **********************************************************************************/ @@ -27,10 +27,12 @@ #include #include #include +#include #if defined(_MSC_VER) +# pragma warning( push ) # pragma warning( disable : 4530 ) # include -# pragma warning( default : 4530 ) +# pragma warning( pop ) #else # include #endif @@ -100,6 +102,94 @@ typedef v8::String::ExternalOneByteStringResource void func(uv_async_t *async) #endif +#if NAUV_UVVERSION >= 0x000b0b + +typedef uv_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t *key) { + return uv_key_create(key); +} + +inline void nauv_key_delete(nauv_key_t *key) { + uv_key_delete(key); +} + +inline void* nauv_key_get(nauv_key_t *key) { + return uv_key_get(key); +} + +inline void nauv_key_set(nauv_key_t *key, void *value) { + uv_key_set(key, value); +} + +#else + +/* Implement thread local storage for older versions of libuv. + * This is essentially a backport of libuv commit 5d2434bf + * written by Ben Noordhuis, adjusted for names and inline. + */ + +#ifndef WIN32 + +#include + +typedef pthread_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + return -pthread_key_create(key, NULL); +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (pthread_key_delete(*key)) + abort(); +} + +inline void* nauv_key_get(nauv_key_t* key) { + return pthread_getspecific(*key); +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (pthread_setspecific(*key, value)) + abort(); +} + +#else + +#include + +typedef struct { + DWORD tls_index; +} nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + key->tls_index = TlsAlloc(); + if (key->tls_index == TLS_OUT_OF_INDEXES) + return UV_ENOMEM; + return 0; +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (TlsFree(key->tls_index) == FALSE) + abort(); + key->tls_index = TLS_OUT_OF_INDEXES; +} + +inline void* nauv_key_get(nauv_key_t* key) { + void* value = TlsGetValue(key->tls_index); + if (value == NULL) + if (GetLastError() != ERROR_SUCCESS) + abort(); + return value; +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (TlsSetValue(key->tls_index, value) == FALSE) + abort(); +} + +#endif +#endif + // some generic helpers template NAN_INLINE bool NanSetPointerSafe( @@ -172,9 +262,14 @@ NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { return val; } +template +NAN_INLINE v8::Local _NanEnsureLocal(T val) { + return NanNew(val); +} + /* io.js 1.0 */ #if NODE_MODULE_VERSION >= IOJS_1_0_MODULE_VERSION \ - || NODE_VERSION_AT_LEAST(0, 11, 15) + || NODE_VERSION_AT_LEAST(0, 11, 15) NAN_INLINE void NanSetCounterFunction(v8::CounterLookupCallback cb) { v8::Isolate::GetCurrent()->SetCounterFunction(cb); @@ -303,14 +398,16 @@ NAN_INLINE v8::Local _NanEnsureLocal(v8::Local val) { # define NanEscapeScope(val) scope.Escape(_NanEnsureLocal(val)) # define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) # define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) +# define NanReturnValue(value) return args.GetReturnValue().Set(_NanEnsureLocal(value)) # define NanReturnUndefined() return # define NanReturnHolder() NanReturnValue(args.Holder()) # define NanReturnThis() NanReturnValue(args.This()) # define NanReturnNull() return args.GetReturnValue().SetNull() # define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() -# define NanObjectWrapHandle(obj) obj->handle() + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return const_cast(obj)->handle(); + } NAN_INLINE v8::Local NanUndefined() { NanEscapableScope(); @@ -839,13 +936,16 @@ NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( # define NanEscapeScope(val) scope.Close(val) # define NanLocker() v8::Locker locker # define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) +# define NanReturnValue(value) return scope.Close(_NanEnsureLocal(value)) # define NanReturnHolder() NanReturnValue(args.Holder()) # define NanReturnThis() NanReturnValue(args.This()) # define NanReturnUndefined() return v8::Undefined() # define NanReturnNull() return v8::Null() # define NanReturnEmptyString() return v8::String::Empty() -# define NanObjectWrapHandle(obj) v8::Local::New(obj->handle_) + + NAN_INLINE v8::Local NanObjectWrapHandle(const node::ObjectWrap *obj) { + return v8::Local::New(obj->handle_); + } NAN_INLINE v8::Local NanUndefined() { NanEscapableScope(); @@ -1393,6 +1493,17 @@ class NanCallback { NanDisposePersistent(handle); } + bool operator==(const NanCallback &other) const { + NanScope(); + v8::Local a = NanNew(handle)->Get(kCallbackIndex); + v8::Local b = NanNew(other.handle)->Get(kCallbackIndex); + return a->StrictEquals(b); + } + + bool operator!=(const NanCallback &other) const { + return !this->operator==(other); + } + NAN_INLINE void SetFunction(const v8::Handle &fn) { NanScope(); NanNew(handle)->Set(kCallbackIndex, fn); @@ -1476,7 +1587,6 @@ class NanCallback { } }; - /* abstract */ class NanAsyncWorker { public: explicit NanAsyncWorker(NanCallback *callback_) diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h b/node_modules/nan/nan_implementation_12_inl.h similarity index 96% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h rename to node_modules/nan/nan_implementation_12_inl.h index ff63ec0..fc0e0ac 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_implementation_12_inl.h +++ b/node_modules/nan/nan_implementation_12_inl.h @@ -13,9 +13,10 @@ //============================================================================== #if defined(_MSC_VER) +# pragma warning( push ) # pragma warning( disable : 4530 ) # include -# pragma warning( default : 4530 ) +# pragma warning( pop ) #else # include #endif @@ -175,10 +176,8 @@ Factory::New( v8::Local source //=== Signature ================================================================ Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv); +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); } //=== String =================================================================== diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/nan/nan_implementation_pre_12_inl.h similarity index 96% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h rename to node_modules/nan/nan_implementation_pre_12_inl.h index 85dd275..e995a14 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h +++ b/node_modules/nan/nan_implementation_pre_12_inl.h @@ -12,10 +12,11 @@ #include #if defined(_MSC_VER) +# pragma warning( push ) # pragma warning( disable : 4530 ) # include # include -# pragma warning( default : 4530 ) +# pragma warning( pop ) #else # include # include @@ -181,10 +182,8 @@ Factory::New( v8::Local source //=== Signature ================================================================ Factory::return_t -Factory::New( Factory::FTH receiver - , int argc - , Factory::FTH argv[]) { - return v8::Signature::New(receiver, argc, argv); +Factory::New(Factory::FTH receiver) { + return v8::Signature::New(receiver); } //=== String =================================================================== diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h b/node_modules/nan/nan_new.h similarity index 98% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h rename to node_modules/nan/nan_new.h index 95b6b51..c189092 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_new.h +++ b/node_modules/nan/nan_new.h @@ -10,9 +10,10 @@ #define NAN_NEW_H_ #if defined(_MSC_VER) +# pragma warning( push ) # pragma warning( disable : 4530 ) # include -# pragma warning( default : 4530 ) +# pragma warning( pop ) #else # include #endif @@ -148,9 +149,7 @@ struct Factory : FactoryBase { template <> struct Factory : FactoryBase { typedef v8::Handle FTH; - static inline - return_t - New( FTH receiver = FTH(), int argc = 0, FTH argv[] = NULL ); + static inline return_t New(FTH receiver = FTH()); }; template <> diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_string_bytes.h b/node_modules/nan/nan_string_bytes.h similarity index 100% rename from node_modules/mongoose/node_modules/mongodb/node_modules/bson/node_modules/nan/nan_string_bytes.h rename to node_modules/nan/nan_string_bytes.h diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json b/node_modules/nan/package.json similarity index 56% rename from node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json rename to node_modules/nan/package.json index 63259da..d73ef84 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json +++ b/node_modules/nan/package.json @@ -1,16 +1,32 @@ { - "name": "nan", - "version": "1.6.2", - "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", - "main": "include_dirs.js", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/nan.git" + "_from": "nan@~1.8", + "_id": "nan@1.8.4", + "_inBundle": false, + "_integrity": "sha1-PHa1OC6rM+RLdY0oE8qdkuk0LzQ=", + "_location": "/nan", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "nan@~1.8", + "name": "nan", + "escapedName": "nan", + "rawSpec": "~1.8", + "saveSpec": null, + "fetchSpec": "~1.8" }, - "scripts": { - "test": "tap --gc test/js/*-test.js", - "rebuild-tests": "pangyp rebuild --directory test" + "_requiredBy": [ + "/bson", + "/kerberos" + ], + "_resolved": "http://registry.npmjs.org/nan/-/nan-1.8.4.tgz", + "_shasum": "3c76b5382eab33e44b758d2813ca9d92e9342f34", + "_spec": "nan@~1.8", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\bson", + "bugs": { + "url": "https://github.com/iojs/nan/issues" }, + "bundleDependencies": false, "contributors": [ { "name": "Rod Vagg", @@ -48,41 +64,26 @@ "url": "https://github.com/agnat" } ], + "deprecated": false, + "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", "devDependencies": { "bindings": "~1.2.1", "node-gyp": "~1.0.2", "pangyp": "~2.0.1", - "tap": "~0.5.0", + "tap": "~0.7.1", "xtend": "~4.0.0" }, + "homepage": "https://github.com/iojs/nan#readme", "license": "MIT", - "gitHead": "ab0e5eed8d4aa36111bf8f44cf75644ece327e98", - "bugs": { - "url": "https://github.com/rvagg/nan/issues" - }, - "homepage": "https://github.com/rvagg/nan", - "_id": "nan@1.6.2", - "_shasum": "2657d1c43b00f1e847e083832285b7d8f5ba8ec8", - "_from": "nan@1.6.2", - "_npmVersion": "2.0.0", - "_npmUser": { - "name": "kkoopa", - "email": "bbyholm@abo.fi" + "main": "include_dirs.js", + "name": "nan", + "repository": { + "type": "git", + "url": "git://github.com/iojs/nan.git" }, - "maintainers": [ - { - "name": "rvagg", - "email": "rod@vagg.org" - }, - { - "name": "kkoopa", - "email": "bbyholm@abo.fi" - } - ], - "dist": { - "shasum": "2657d1c43b00f1e847e083832285b7d8f5ba8ec8", - "tarball": "http://registry.npmjs.org/nan/-/nan-1.6.2.tgz" + "scripts": { + "rebuild-tests": "pangyp rebuild --directory test", + "test": "tap --gc test/js/*-test.js" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/nan/-/nan-1.6.2.tgz" + "version": "1.8.4" } diff --git a/node_modules/readable-stream/.airtap.yml b/node_modules/readable-stream/.airtap.yml new file mode 100644 index 0000000..38e6f03 --- /dev/null +++ b/node_modules/readable-stream/.airtap.yml @@ -0,0 +1,17 @@ +sauce_connect: true +browsers: + - name: chrome + version: latest + platform: Windows 10 + - name: internet explorer + version: latest + platform: Windows 10 + - name: firefox + version: latest + platform: Windows 10 + - name: safari + version: latest + platform: Mac 10.13 + - name: microsoftedge + version: latest + platform: Windows 10 diff --git a/node_modules/readable-stream/.airtaprc b/node_modules/readable-stream/.airtaprc new file mode 100644 index 0000000..02edbf5 --- /dev/null +++ b/node_modules/readable-stream/.airtaprc @@ -0,0 +1,2 @@ +sauce_username: readable-stream +sauce_key: d0102427-0213-4532-bd61-ee19f02ac521 diff --git a/node_modules/readable-stream/.travis.yml b/node_modules/readable-stream/.travis.yml new file mode 100644 index 0000000..94374dc --- /dev/null +++ b/node_modules/readable-stream/.travis.yml @@ -0,0 +1,22 @@ +sudo: false +language: node_js +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: 6 + env: CMD=test + - node_js: 8 + env: CMD=test + - node_js: 9 + env: CMD=test + - node_js: 10 + env: CMD=test + - node_js: stable + env: CMD=test-browsers + addons: + sauce_connect: true + hosts: + - airtap.local +script: npm run $CMD diff --git a/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000..f478d58 --- /dev/null +++ b/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/readable-stream/GOVERNANCE.md b/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000..16ffb93 --- /dev/null +++ b/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..2873b3b --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..afd6958 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,111 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.11.0/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` supports Node 6, 8, and 10, as well as +evergreen browsers, IE 11 and latest Safari. The breaking changes +introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) +and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x + +v2.x.x of `readable-stream` supports all Node.js version from 0.8, as well as +evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/readable-stream/errors-browser.js b/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000..ef7d85b --- /dev/null +++ b/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,131 @@ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = function (_Base) { + _inherits(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + _classCallCheck(this, NodeError); + + return _possibleConstructorReturn(this, (NodeError.__proto__ || Object.getPrototypeOf(NodeError)).call(this, getMessage(arg1, arg2, arg3))); + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + if (len > 2) { + return 'one of ' + thing + ' ' + expected.slice(0, len - 1).join(', ') + ', or ' + expected[len - 1]; + } else if (len === 2) { + return 'one of ' + thing + ' ' + expected[0] + ' or ' + expected[1]; + } else { + return 'of ' + thing + ' ' + expected[0]; + } + } else { + return 'of ' + thing + ' ' + String(expected); + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner = void 0; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg = void 0; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = 'The ' + name + ' ' + determiner + ' ' + oneOf(expected, 'type'); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = 'The "' + name + '" ' + type + ' ' + determiner + ' ' + oneOf(expected, 'type'); + } + + msg += '. Received type ' + (typeof actual === 'undefined' ? 'undefined' : _typeof(actual)); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/errors.js b/node_modules/readable-stream/errors.js new file mode 100644 index 0000000..8471526 --- /dev/null +++ b/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/readable-stream/experimentalWarning.js b/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000..78e8414 --- /dev/null +++ b/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..e30f646 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,141 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + + if (options) { + if (options.readable === false) this.readable = false; + + if (options.writable === false) this.writable = false; + + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } +}); + +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js similarity index 82% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js rename to node_modules/readable-stream/lib/_stream_passthrough.js index 895ca50..a3ab801 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -23,24 +23,20 @@ // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. +'use strict'; + module.exports = PassThrough; var Transform = require('./_stream_transform'); -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); +require('inherits')(PassThrough, Transform); function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } -PassThrough.prototype._transform = function(chunk, encoding, cb) { +PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); -}; +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..668c218 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1047 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +var _require2 = require('../experimentalWarning'), + emitExperimentalWarning = _require2.emitExperimentalWarning; + +// Lazy loaded to improve the startup performance. + + +var StringDecoder = void 0; +var ReadableAsyncIterator = void 0; + +require('inherits')(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + // if setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + + return res; +}; + +function updateReadableListening(self) { + self._readableState.readableListening = self.listenerCount('readable') > 0; + + // crude way to check if we should resume + if (self.listenerCount('data') > 0) { + self.resume(); + } +} + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + emitExperimentalWarning('Readable[Symbol.asyncIterator]'); + if (ReadableAsyncIterator === undefined) ReadableAsyncIterator = require('./internal/streams/async_iterator'); + return new ReadableAsyncIterator(this); + }; +} + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer; + } +}); + +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.flowing; + }, + set: function (state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js similarity index 69% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js rename to node_modules/readable-stream/lib/_stream_transform.js index eb188df..0db2539 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -19,7 +19,6 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. - // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where @@ -62,65 +61,58 @@ // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ +'use strict'; -util.inherits(Transform, Duplex); +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; +var Duplex = require('./_stream_duplex'); - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} +require('inherits')(Transform, Duplex); -function afterTransform(stream, er, data) { - var ts = stream._transformState; +function afterTransform(er, data) { + var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } ts.writechunk = null; ts.writecb = null; - if (data !== null && data !== undefined) - stream.push(data); + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); - if (cb) - cb(er); + cb(er); - var rs = stream._readableState; + var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + this._read(rs.highWaterMark); } } - function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); + if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; @@ -130,17 +122,29 @@ function Transform(options) { // sync guard flag. this._readableState.sync = false; - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } } -Transform.prototype.push = function(chunk, encoding) { +Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; @@ -155,31 +159,28 @@ Transform.prototype.push = function(chunk, encoding) { // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; -Transform.prototype._write = function(chunk, encoding, cb) { +Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { +Transform.prototype._read = function (n) { var ts = this._transformState; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { @@ -189,22 +190,23 @@ Transform.prototype._read = function(n) { } }; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; -function done(stream, er) { - if (er) - return stream.emit('error', er); +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); -} +} \ No newline at end of file diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..a5bb22d --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,701 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +var destroyImpl = require('./internal/streams/destroy'); + +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; + +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; + +require('inherits')(Writable, Stream); + +function nop() {} + +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + stream.emit('error', er); + process.nextTick(cb, er); + return false; + } + return true; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + this._writableState.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState && this._writableState.getBuffer(); + } +}); + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + + return this; +}; + +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.length; + } +}); + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000..290ad1d --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,174 @@ +'use strict'; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +var AsyncIteratorRecord = function AsyncIteratorRecord(value, done) { + _classCallCheck(this, AsyncIteratorRecord); + + this.done = done; + this.value = value; +}; + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(new AsyncIteratorRecord(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function onEnd(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(new AsyncIteratorRecord(null, true)); + } + iter[kEnded] = true; +} + +function onError(iter, err) { + var reject = iter[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + reject(err); + } + iter[kError] = err; +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var ReadableAsyncIterator = function () { + function ReadableAsyncIterator(stream) { + var _this = this; + + _classCallCheck(this, ReadableAsyncIterator); + + this[kStream] = stream; + this[kLastResolve] = null; + this[kLastReject] = null; + this[kError] = null; + this[kEnded] = false; + this[kLastPromise] = null; + + stream.on('readable', onReadable.bind(null, this)); + stream.on('end', onEnd.bind(null, this)); + stream.on('error', onError.bind(null, this)); + + // the function passed to new Promise + // is cached so we avoid allocating a new + // closure at every run + this[kHandlePromise] = function (resolve, reject) { + var data = _this[kStream].read(); + if (data) { + _this[kLastPromise] = null; + _this[kLastResolve] = null; + _this[kLastReject] = null; + resolve(new AsyncIteratorRecord(data, false)); + } else { + _this[kLastResolve] = resolve; + _this[kLastReject] = reject; + } + }; + } + + ReadableAsyncIterator.prototype.next = function next() { + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(new AsyncIteratorRecord(null, true)); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise = void 0; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(new AsyncIteratorRecord(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + + return promise; + }; + + ReadableAsyncIterator.prototype.return = function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(new AsyncIteratorRecord(null, true)); + }); + }); + }; + + _createClass(ReadableAsyncIterator, [{ + key: 'stream', + get: function () { + return this[kStream]; + } + }]); + + return ReadableAsyncIterator; +}(); + +module.exports = ReadableAsyncIterator; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000..24ed313 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,163 @@ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _require = require('buffer'), + Buffer = _require.Buffer; + +var _require2 = require('util'), + inspect = _require2.inspect; + +var custom = inspect && custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Consumes a specified amount of bytes or characters from the buffered data. + + + BufferList.prototype.consume = function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + }; + + BufferList.prototype.first = function first() { + return this.head.data; + }; + + // Consumes a specified amount of characters from the buffered data. + + + BufferList.prototype._getString = function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + }; + + // Consumes a specified amount of bytes from the buffered data. + + + BufferList.prototype._getBuffer = function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + }; + + BufferList.prototype[custom] = function () { + var obj = inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; + + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000..51efdef --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,86 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API + +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + process.nextTick(emitErrorNT, this, err); + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + process.nextTick(emitErrorAndCloseNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + + return this; +} + +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} + +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000..5507865 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,94 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function once(callback) { + var called = false; + return function (err) { + if (called) return; + called = true; + callback.call(this, err); + }; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function () { + if (!stream.writable) onfinish(); + }; + + var onfinish = function () { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function () { + readable = false; + if (!writable) callback.call(stream); + }; + + var onerror = function (err) { + callback.call(stream, err); + }; + + var onclose = function () { + if (readable && !(rs && rs.ended)) { + return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); + } + if (writable && !(ws && ws.ended)) { + return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()); + } + }; + + var onrequest = function () { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !ws) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000..792f0ab --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,99 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos = void 0; + +function once(callback) { + var called = false;return function () { + if (called) return;called = true;callback.apply(undefined, arguments); + }; +} + +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + + var closed = false; + stream.on('close', function () { + closed = true; + }); + + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { readable: reading, writable: writing }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error = void 0; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + + return streams.reduce(pipe); +} + +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000..66131e4 --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,25 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!Number.isInteger(hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000..9332a3f --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000..ce2ad5b --- /dev/null +++ b/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..1b7443e --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,109 @@ +{ + "_from": "readable-stream@latest", + "_id": "readable-stream@3.0.6", + "_inBundle": false, + "_integrity": "sha512-9E1oLoOWfhSXHGv6QlwXJim7uNzd9EVlWK+21tCU9Ju/kR0/p2AZYPz4qSchgO8PlLIH4FpZYfzwS+rEksZjIg==", + "_location": "/readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "readable-stream@latest", + "name": "readable-stream", + "escapedName": "readable-stream", + "rawSpec": "latest", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.0.6.tgz", + "_shasum": "351302e4c68b5abd6a2ed55376a7f9a25be3057a", + "_spec": "readable-stream@latest", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb", + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "bugs": { + "url": "https://github.com/nodejs/readable-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "deprecated": false, + "description": "Streams3, a user-land copy of the stream library from Node.js", + "devDependencies": { + "airtap": "0.0.9", + "assert": "^1.4.0", + "babel-cli": "^6.26.0", + "babel-core": "^6.26.3", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-plugin-transform-async-to-generator": "^6.24.1", + "babel-plugin-transform-es2015-arrow-functions": "^6.5.2", + "babel-plugin-transform-es2015-block-scoping": "^6.26.0", + "babel-plugin-transform-es2015-classes": "^6.24.1", + "babel-plugin-transform-es2015-computed-properties": "^6.24.1", + "babel-plugin-transform-es2015-destructuring": "^6.18.0", + "babel-plugin-transform-es2015-for-of": "^6.8.0", + "babel-plugin-transform-es2015-parameters": "^6.24.1", + "babel-plugin-transform-es2015-shorthand-properties": "^6.24.1", + "babel-plugin-transform-es2015-spread": "^6.22.0", + "babel-plugin-transform-es2015-template-literals": "^6.8.0", + "babel-plugin-transform-inline-imports-commonjs": "^1.2.0", + "babel-polyfill": "^6.9.1", + "babel-preset-env": "^1.7.0", + "bl": "^2.0.0", + "buffer": "^5.1.0", + "deep-strict-equal": "^0.2.0", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^11.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "engines": { + "node": ">= 6" + }, + "homepage": "https://github.com/nodejs/readable-stream#readme", + "keywords": [ + "readable", + "stream", + "pipe" + ], + "license": "MIT", + "main": "readable.js", + "name": "readable-stream", + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream.git" + }, + "scripts": { + "ci": "TAP=1 tap test/parallel/*.js test/ours/*.js | tee test.tap", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "test": "tap -j 4 test/parallel/*.js test/ours/*.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "update-browser-errors": "babel --presets env -o errors-browser.js errors.js" + }, + "version": "3.0.6" +} diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable-browser.js similarity index 72% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js rename to node_modules/readable-stream/readable-browser.js index 8b5337b..e503725 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/readable.js +++ b/node_modules/readable-stream/readable-browser.js @@ -1,6 +1,5 @@ -var Stream = require('stream'); // hack to fix a circular dependency issue when used with browserify exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = Stream; +exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..aeec0df --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,21 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/mongoose/node_modules/regexp-clone/.npmignore b/node_modules/regexp-clone/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/.npmignore rename to node_modules/regexp-clone/.npmignore diff --git a/node_modules/mongoose/node_modules/regexp-clone/.travis.yml b/node_modules/regexp-clone/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/.travis.yml rename to node_modules/regexp-clone/.travis.yml diff --git a/node_modules/mongoose/node_modules/regexp-clone/History.md b/node_modules/regexp-clone/History.md similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/History.md rename to node_modules/regexp-clone/History.md diff --git a/node_modules/mongoose/node_modules/regexp-clone/LICENSE b/node_modules/regexp-clone/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/LICENSE rename to node_modules/regexp-clone/LICENSE diff --git a/node_modules/mongoose/node_modules/regexp-clone/Makefile b/node_modules/regexp-clone/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/Makefile rename to node_modules/regexp-clone/Makefile diff --git a/node_modules/mongoose/node_modules/regexp-clone/README.md b/node_modules/regexp-clone/README.md similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/README.md rename to node_modules/regexp-clone/README.md diff --git a/node_modules/mongoose/node_modules/regexp-clone/index.js b/node_modules/regexp-clone/index.js similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/index.js rename to node_modules/regexp-clone/index.js diff --git a/node_modules/mongoose/node_modules/regexp-clone/package.json b/node_modules/regexp-clone/package.json similarity index 57% rename from node_modules/mongoose/node_modules/regexp-clone/package.json rename to node_modules/regexp-clone/package.json index 8ef9b17..12d2e53 100644 --- a/node_modules/mongoose/node_modules/regexp-clone/package.json +++ b/node_modules/regexp-clone/package.json @@ -1,47 +1,71 @@ { - "name": "regexp-clone", - "version": "0.0.1", - "description": "Clone RegExps with options", - "main": "index.js", - "scripts": { - "test": "make test" + "_from": "regexp-clone@0.0.1", + "_id": "regexp-clone@0.0.1", + "_inBundle": false, + "_integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=", + "_location": "/regexp-clone", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/regexp-clone.git" + "_npmVersion": "1.2.14", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "regexp-clone@0.0.1", + "name": "regexp-clone", + "escapedName": "regexp-clone", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" }, - "keywords": [ - "RegExp", - "clone" + "_requiredBy": [ + "/mongoose", + "/mquery" ], + "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "_spec": "regexp-clone@0.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", "author": { "name": "Aaron Heckmann", "email": "aaron.heckmann+github@gmail.com" }, - "license": "MIT", + "bugs": { + "url": "https://github.com/aheckmann/regexp-clone/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Clone RegExps with options", "devDependencies": { "mocha": "1.8.1" }, - "readme": "#regexp-clone\n==============\n\nClones RegExps with flag preservation\n\n```js\nvar regexpClone = require('regexp-clone');\n\nvar a = /somethin/g;\nconsole.log(a.global); // true\n\nvar b = regexpClone(a);\nconsole.log(b.global); // true\n```\n\n## License\n\n[MIT](https://github.com/aheckmann/regexp-clone/blob/master/LICENSE)\n", - "readmeFilename": "README.md", - "_id": "regexp-clone@0.0.1", + "directories": {}, "dist": { "shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", "tarball": "http://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz" }, - "_from": "regexp-clone@0.0.1", - "_npmVersion": "1.2.14", - "_npmUser": { - "name": "aaron", - "email": "aaron.heckmann+github@gmail.com" - }, + "homepage": "https://github.com/aheckmann/regexp-clone#readme", + "keywords": [ + "RegExp", + "clone" + ], + "license": "MIT", + "main": "index.js", "maintainers": [ { "name": "aaron", "email": "aaron.heckmann+github@gmail.com" } ], - "directories": {}, - "_shasum": "a7c2e09891fdbf38fbb10d376fb73003e68ac589", - "_resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz" + "name": "regexp-clone", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/regexp-clone.git" + }, + "scripts": { + "test": "make test" + }, + "version": "0.0.1" } diff --git a/node_modules/mongoose/node_modules/regexp-clone/test/index.js b/node_modules/regexp-clone/test/index.js similarity index 100% rename from node_modules/mongoose/node_modules/regexp-clone/test/index.js rename to node_modules/regexp-clone/test/index.js diff --git a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE b/node_modules/safe-buffer/LICENSE similarity index 62% rename from node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE rename to node_modules/safe-buffer/LICENSE index e3d4e69..0c068ce 100644 --- a/node_modules/mongoose/node_modules/mongodb/node_modules/readable-stream/LICENSE +++ b/node_modules/safe-buffer/LICENSE @@ -1,9 +1,12 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + 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 +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 @@ -13,6 +16,6 @@ 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. +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. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..22438da --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..dd384db --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,62 @@ +{ + "_from": "safe-buffer@~5.1.0", + "_id": "safe-buffer@5.1.2", + "_inBundle": false, + "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@~5.1.0", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "~5.1.0", + "saveSpec": null, + "fetchSpec": "~5.1.0" + }, + "_requiredBy": [ + "/string_decoder" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", + "_spec": "safe-buffer@~5.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\string_decoder", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "types": "index.d.ts", + "version": "5.1.2" +} diff --git a/node_modules/mongoose/node_modules/sliced/.npmignore b/node_modules/sliced/.npmignore similarity index 100% rename from node_modules/mongoose/node_modules/sliced/.npmignore rename to node_modules/sliced/.npmignore diff --git a/node_modules/mongoose/node_modules/sliced/.travis.yml b/node_modules/sliced/.travis.yml similarity index 100% rename from node_modules/mongoose/node_modules/sliced/.travis.yml rename to node_modules/sliced/.travis.yml diff --git a/node_modules/mongoose/node_modules/sliced/History.md b/node_modules/sliced/History.md similarity index 100% rename from node_modules/mongoose/node_modules/sliced/History.md rename to node_modules/sliced/History.md diff --git a/node_modules/mongoose/node_modules/sliced/LICENSE b/node_modules/sliced/LICENSE similarity index 100% rename from node_modules/mongoose/node_modules/sliced/LICENSE rename to node_modules/sliced/LICENSE diff --git a/node_modules/mongoose/node_modules/sliced/Makefile b/node_modules/sliced/Makefile similarity index 100% rename from node_modules/mongoose/node_modules/sliced/Makefile rename to node_modules/sliced/Makefile diff --git a/node_modules/mongoose/node_modules/sliced/README.md b/node_modules/sliced/README.md similarity index 100% rename from node_modules/mongoose/node_modules/sliced/README.md rename to node_modules/sliced/README.md diff --git a/node_modules/mongoose/node_modules/sliced/bench.js b/node_modules/sliced/bench.js similarity index 100% rename from node_modules/mongoose/node_modules/sliced/bench.js rename to node_modules/sliced/bench.js diff --git a/node_modules/mongoose/node_modules/sliced/component.json b/node_modules/sliced/component.json similarity index 100% rename from node_modules/mongoose/node_modules/sliced/component.json rename to node_modules/sliced/component.json diff --git a/node_modules/mongoose/node_modules/sliced/index.js b/node_modules/sliced/index.js similarity index 100% rename from node_modules/mongoose/node_modules/sliced/index.js rename to node_modules/sliced/index.js diff --git a/node_modules/mongoose/node_modules/sliced/lib/sliced.js b/node_modules/sliced/lib/sliced.js similarity index 100% rename from node_modules/mongoose/node_modules/sliced/lib/sliced.js rename to node_modules/sliced/lib/sliced.js diff --git a/node_modules/sliced/package.json b/node_modules/sliced/package.json new file mode 100644 index 0000000..84da1fe --- /dev/null +++ b/node_modules/sliced/package.json @@ -0,0 +1,73 @@ +{ + "_from": "sliced@0.0.5", + "_id": "sliced@0.0.5", + "_inBundle": false, + "_integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=", + "_location": "/sliced", + "_npmUser": { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + }, + "_npmVersion": "1.1.59", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "sliced@0.0.5", + "name": "sliced", + "escapedName": "sliced", + "rawSpec": "0.0.5", + "saveSpec": null, + "fetchSpec": "0.0.5" + }, + "_requiredBy": [ + "/mongoose", + "/mquery" + ], + "_resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "_shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "_spec": "sliced@0.0.5", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", + "author": { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + "bugs": { + "url": "https://github.com/aheckmann/sliced/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A faster Node.js alternative to Array.prototype.slice.call(arguments)", + "devDependencies": { + "benchmark": "~1.0.0", + "mocha": "1.5.0" + }, + "directories": {}, + "dist": { + "shasum": "5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "tarball": "http://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz" + }, + "homepage": "https://github.com/aheckmann/sliced#readme", + "keywords": [ + "arguments", + "slice", + "array" + ], + "license": "MIT", + "main": "index.js", + "maintainers": [ + { + "name": "aaron", + "email": "aaron.heckmann+github@gmail.com" + } + ], + "name": "sliced", + "repository": { + "type": "git", + "url": "git://github.com/aheckmann/sliced.git" + }, + "scripts": { + "test": "make test" + }, + "version": "0.0.5" +} diff --git a/node_modules/mongoose/node_modules/sliced/test/index.js b/node_modules/sliced/test/index.js similarity index 100% rename from node_modules/mongoose/node_modules/sliced/test/index.js rename to node_modules/sliced/test/index.js diff --git a/node_modules/string_decoder/.travis.yml b/node_modules/string_decoder/.travis.yml new file mode 100644 index 0000000..3347a72 --- /dev/null +++ b/node_modules/string_decoder/.travis.yml @@ -0,0 +1,50 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.10' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.11' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.12' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 1 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 2 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 3 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 6 + env: TASK=test + - node_js: 7 + env: TASK=test + - node_js: 8 + env: TASK=test + - node_js: 9 + env: TASK=test diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..778edb2 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..5fd5831 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000..2e89e63 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..9b0078f --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,59 @@ +{ + "_from": "string_decoder@^1.1.1", + "_id": "string_decoder@1.1.1", + "_inBundle": false, + "_integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "_location": "/string_decoder", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string_decoder@^1.1.1", + "name": "string_decoder", + "escapedName": "string_decoder", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "_shasum": "9cf1611ba62685d7030ae9e4ba34149c3af03fc8", + "_spec": "string_decoder@^1.1.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\readable-stream", + "bugs": { + "url": "https://github.com/nodejs/string_decoder/issues" + }, + "bundleDependencies": false, + "dependencies": { + "safe-buffer": "~5.1.0" + }, + "deprecated": false, + "description": "The string_decoder module from Node core", + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "main": "lib/string_decoder.js", + "name": "string_decoder", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "scripts": { + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", + "test": "tap test/parallel/*.js && node test/verify-dependencies" + }, + "version": "1.1.1" +} diff --git a/node_modules/util-deprecate/History.md b/node_modules/util-deprecate/History.md new file mode 100644 index 0000000..acc8675 --- /dev/null +++ b/node_modules/util-deprecate/History.md @@ -0,0 +1,16 @@ + +1.0.2 / 2015-10-07 +================== + + * use try/catch when checking `localStorage` (#3, @kumavis) + +1.0.1 / 2014-11-25 +================== + + * browser: use `console.warn()` for deprecation calls + * browser: more jsdocs + +1.0.0 / 2014-04-30 +================== + + * initial commit diff --git a/node_modules/util-deprecate/LICENSE b/node_modules/util-deprecate/LICENSE new file mode 100644 index 0000000..6a60e8c --- /dev/null +++ b/node_modules/util-deprecate/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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. diff --git a/node_modules/util-deprecate/README.md b/node_modules/util-deprecate/README.md new file mode 100644 index 0000000..75622fa --- /dev/null +++ b/node_modules/util-deprecate/README.md @@ -0,0 +1,53 @@ +util-deprecate +============== +### The Node.js `util.deprecate()` function with browser support + +In Node.js, this module simply re-exports the `util.deprecate()` function. + +In the web browser (i.e. via browserify), a browser-specific implementation +of the `util.deprecate()` function is used. + + +## API + +A `deprecate()` function is the only thing exposed by this module. + +``` javascript +// setup: +exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); + + +// users see: +foo(); +// foo() is deprecated, use bar() instead +foo(); +foo(); +``` + + +## License + +(The MIT License) + +Copyright (c) 2014 Nathan Rajlich + +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. diff --git a/node_modules/util-deprecate/browser.js b/node_modules/util-deprecate/browser.js new file mode 100644 index 0000000..549ae2f --- /dev/null +++ b/node_modules/util-deprecate/browser.js @@ -0,0 +1,67 @@ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} diff --git a/node_modules/util-deprecate/node.js b/node_modules/util-deprecate/node.js new file mode 100644 index 0000000..5e6fcff --- /dev/null +++ b/node_modules/util-deprecate/node.js @@ -0,0 +1,6 @@ + +/** + * For Node.js, simply re-export the core `util.deprecate` function. + */ + +module.exports = require('util').deprecate; diff --git a/node_modules/util-deprecate/package.json b/node_modules/util-deprecate/package.json new file mode 100644 index 0000000..2395919 --- /dev/null +++ b/node_modules/util-deprecate/package.json @@ -0,0 +1,56 @@ +{ + "_from": "util-deprecate@^1.0.1", + "_id": "util-deprecate@1.0.2", + "_inBundle": false, + "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "_location": "/util-deprecate", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "util-deprecate@^1.0.1", + "name": "util-deprecate", + "escapedName": "util-deprecate", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "_spec": "util-deprecate@^1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\readable-stream", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/TooTallNate/util-deprecate/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The Node.js `util.deprecate()` function with browser support", + "homepage": "https://github.com/TooTallNate/util-deprecate", + "keywords": [ + "util", + "deprecate", + "browserify", + "browser", + "node" + ], + "license": "MIT", + "main": "node.js", + "name": "util-deprecate", + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/util-deprecate.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "version": "1.0.2" +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..eda34b4 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,543 @@ +{ + "name": "starter-node-angular", + "version": "1.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "bluebird": { + "version": "2.10.2", + "resolved": "http://registry.npmjs.org/bluebird/-/bluebird-2.10.2.tgz", + "integrity": "sha1-AkpVFylTCIV/FPkfEQb8O1VfRGs=" + }, + "body-parser": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.4.3.tgz", + "integrity": "sha1-RyeVLP9K8Hc+76SyJsL0Ei9eI00=", + "requires": { + "bytes": "1.0.0", + "depd": "0.3.0", + "iconv-lite": "0.4.3", + "media-typer": "0.2.0", + "qs": "0.6.6", + "raw-body": "1.2.2", + "type-is": "1.3.1" + }, + "dependencies": { + "bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-1.0.0.tgz", + "integrity": "sha1-NWnt6Lo0MV+rmcPpLLBMciDeH6g=" + }, + "depd": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-0.3.0.tgz", + "integrity": "sha1-Ecm8KOQlMl+9iziUC+/2n6UyaIM=" + }, + "iconv-lite": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.3.tgz", + "integrity": "sha1-nniHeTt2nMaV6yLSVGpP0tebeh4=" + }, + "media-typer": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", + "integrity": "sha1-2KBlITrf6qLnYyGitt2jb/YzWYQ=" + }, + "qs": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz", + "integrity": "sha1-bgFQmP9RlouKPIGQAdXyyJvEsQc=" + }, + "raw-body": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-1.2.2.tgz", + "integrity": "sha1-DGjh7ijP7X26SCIjSuxgeEYcvB8=", + "requires": { + "bytes": "1", + "iconv-lite": "0.4.3" + } + }, + "type-is": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.1.tgz", + "integrity": "sha1-pnibWlITgomt4e+PbZ8odP/XC2s=", + "requires": { + "media-typer": "0.2.0", + "mime-types": "1.0.0" + }, + "dependencies": { + "mime-types": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.0.tgz", + "integrity": "sha1-antKavLn2S+Xr+A/BHx4AejwAdI=" + } + } + } + } + }, + "bson": { + "version": "0.2.22", + "resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", + "integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", + "requires": { + "nan": "~1.8" + } + }, + "debug": { + "version": "2.2.0", + "resolved": "http://registry.npmjs.org/debug/-/debug-2.2.0.tgz", + "integrity": "sha1-+HBX6ZWxofauaklgZkE3vFbwOdo=", + "requires": { + "ms": "0.7.1" + }, + "dependencies": { + "ms": { + "version": "0.7.1", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.7.1.tgz", + "integrity": "sha1-nNE8A62/8ltl7/3nzoZO6VIBcJg=" + } + } + }, + "express": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.5.1.tgz", + "integrity": "sha1-S8Pm7J2yjldf5ZHDb7t4H/72/nw=", + "requires": { + "accepts": "~1.0.7", + "buffer-crc32": "0.2.3", + "cookie": "0.1.2", + "cookie-signature": "1.0.4", + "debug": "1.0.2", + "depd": "0.3.0", + "escape-html": "1.0.1", + "finalhandler": "0.0.2", + "fresh": "0.2.2", + "media-typer": "0.2.0", + "merge-descriptors": "0.0.2", + "methods": "1.0.1", + "parseurl": "1.0.1", + "path-to-regexp": "0.1.2", + "proxy-addr": "1.0.1", + "qs": "0.6.6", + "range-parser": "1.0.0", + "send": "0.5.0", + "serve-static": "~1.3.0", + "type-is": "~1.3.2", + "utils-merge": "1.0.0", + "vary": "0.1.0" + }, + "dependencies": { + "accepts": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz", + "integrity": "sha1-W1AftPBwQwmWTM2wSBclQSCNqxo=", + "requires": { + "mime-types": "~1.0.0", + "negotiator": "0.4.7" + }, + "dependencies": { + "mime-types": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", + "integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=" + }, + "negotiator": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz", + "integrity": "sha1-pBYPcXfsgGc4Yx0NMFIyXaQqvcg=" + } + } + }, + "buffer-crc32": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz", + "integrity": "sha1-u1RRnpXRB8vSQA520MqxRnM22SE=" + }, + "cookie": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz", + "integrity": "sha1-cv7D0k5Io0Mgc9kMEmQgBQYQBLE=" + }, + "cookie-signature": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.4.tgz", + "integrity": "sha1-Dt0iKG46ERuaKnDbNj6SXoZ/aso=" + }, + "debug": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", + "requires": { + "ms": "0.6.2" + }, + "dependencies": { + "ms": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + } + } + }, + "depd": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-0.3.0.tgz", + "integrity": "sha1-Ecm8KOQlMl+9iziUC+/2n6UyaIM=" + }, + "escape-html": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz", + "integrity": "sha1-GBoobq05ejmpKFfPsdQwUuNWv/A=" + }, + "finalhandler": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz", + "integrity": "sha1-BgPYde6H1WeiZmkoFcyK1E/M7to=", + "requires": { + "debug": "1.0.2", + "escape-html": "1.0.1" + } + }, + "fresh": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz", + "integrity": "sha1-lzHc9WeMf660T7kDxPct9VGH+nc=" + }, + "media-typer": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", + "integrity": "sha1-2KBlITrf6qLnYyGitt2jb/YzWYQ=" + }, + "merge-descriptors": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", + "integrity": "sha1-w2pSp4FDdRPFcnXzndnTF1FKyMc=" + }, + "methods": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz", + "integrity": "sha1-dbyRlD3/19oDfPPusO1zoAN80Us=" + }, + "parseurl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", + "integrity": "sha1-Llfc5u/dN8NRhwEDCUTCK/OIt7Q=" + }, + "path-to-regexp": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz", + "integrity": "sha1-mysVH5zDAYye6lDKlXKeBXgXErQ=" + }, + "proxy-addr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz", + "integrity": "sha1-x8Vm1etOP61n7rnHfFVYzMObiKg=", + "requires": { + "ipaddr.js": "0.1.2" + }, + "dependencies": { + "ipaddr.js": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz", + "integrity": "sha1-ah/T2FT1ACllw017vNm0qNSwRn4=" + } + } + }, + "qs": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz", + "integrity": "sha1-bgFQmP9RlouKPIGQAdXyyJvEsQc=" + }, + "range-parser": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz", + "integrity": "sha1-pLJkz+C+XONqvjdlrJwqJIdG28A=" + }, + "send": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.5.0.tgz", + "integrity": "sha1-/A9+L5Limuv9ihst60o5TnpTGmg=", + "requires": { + "debug": "1.0.2", + "escape-html": "1.0.1", + "finished": "1.2.2", + "fresh": "0.2.2", + "mime": "1.2.11", + "ms": "0.6.2", + "range-parser": "~1.0.0" + }, + "dependencies": { + "finished": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", + "integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", + "requires": { + "ee-first": "1.0.3" + }, + "dependencies": { + "ee-first": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", + "integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=" + } + } + }, + "mime": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=" + }, + "ms": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + } + } + }, + "serve-static": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz", + "integrity": "sha1-2QSmy/VfURx4E49vRe5uadnRBco=", + "requires": { + "escape-html": "1.0.1", + "parseurl": "~1.1.3", + "send": "0.6.0" + }, + "dependencies": { + "parseurl": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz", + "integrity": "sha1-HwBXOKxxtBe8LQhFy9+iqLY+pjk=" + }, + "send": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.6.0.tgz", + "integrity": "sha1-pZ2pJl23w1FB4Qec8fNo7g1Zs6s=", + "requires": { + "debug": "1.0.3", + "depd": "0.3.0", + "escape-html": "1.0.1", + "finished": "1.2.2", + "fresh": "0.2.2", + "mime": "1.2.11", + "ms": "0.6.2", + "range-parser": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-1.0.3.tgz", + "integrity": "sha1-/IxrLWACgEtAgcAgjg9kYLofo+Q=", + "requires": { + "ms": "0.6.2" + } + }, + "finished": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", + "integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", + "requires": { + "ee-first": "1.0.3" + }, + "dependencies": { + "ee-first": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", + "integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=" + } + } + }, + "mime": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=" + }, + "ms": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + } + } + } + } + }, + "type-is": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz", + "integrity": "sha1-TypdxYd1yhYwJQr8cYb4s2MJ0bs=", + "requires": { + "media-typer": "0.2.0", + "mime-types": "~1.0.1" + }, + "dependencies": { + "mime-types": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", + "integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=" + } + } + }, + "utils-merge": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", + "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=" + }, + "vary": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz", + "integrity": "sha1-3wlFiZ6TwMxb0YzIMh2dIedPYXY=" + } + } + }, + "hooks": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz", + "integrity": "sha1-D1kbGzRL3LPfWXc/Yvu6+Fv0Aos=" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "optional": true + }, + "kerberos": { + "version": "0.0.11", + "resolved": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.11.tgz", + "integrity": "sha1-yymJHCHCKsGV8xQLl90SIE/qfcI=", + "optional": true, + "requires": { + "nan": "~1.8" + } + }, + "method-override": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/method-override/-/method-override-2.0.2.tgz", + "integrity": "sha1-AFMSeMeXiWQL8n6X4mo6Wh98ynM=", + "requires": { + "methods": "1.0.1", + "parseurl": "1.0.1", + "vary": "0.1.0" + }, + "dependencies": { + "methods": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz", + "integrity": "sha1-dbyRlD3/19oDfPPusO1zoAN80Us=" + }, + "parseurl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", + "integrity": "sha1-Llfc5u/dN8NRhwEDCUTCK/OIt7Q=" + }, + "vary": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz", + "integrity": "sha1-3wlFiZ6TwMxb0YzIMh2dIedPYXY=" + } + } + }, + "mongodb": { + "version": "1.4.38", + "resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", + "integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "requires": { + "bson": "~0.2", + "kerberos": "0.0.11", + "readable-stream": "^3.0.6" + } + }, + "mongoose": { + "version": "3.8.40", + "resolved": "http://registry.npmjs.org/mongoose/-/mongoose-3.8.40.tgz", + "integrity": "sha1-Ay9bpVWCSXVZqHwfP0s5WcJkBqc=", + "requires": { + "hooks": "0.2.1", + "mongodb": "1.4.38", + "mpath": "0.1.1", + "mpromise": "0.4.3", + "mquery": "1.10.0", + "ms": "0.1.0", + "muri": "1.1.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + } + }, + "mpath": { + "version": "0.1.1", + "resolved": "http://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz", + "integrity": "sha1-I9qFK3wjLuCX9HWdKcDunNItXkY=" + }, + "mpromise": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.4.3.tgz", + "integrity": "sha1-7cR6daKhd7DpOCc121Lb7DgIzDM=" + }, + "mquery": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/mquery/-/mquery-1.10.0.tgz", + "integrity": "sha1-hgPwKwtSTResBTmoWZYSTuF7fLM=", + "requires": { + "bluebird": "2.10.2", + "debug": "2.2.0", + "regexp-clone": "0.0.1", + "sliced": "0.0.5" + } + }, + "ms": { + "version": "0.1.0", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.1.0.tgz", + "integrity": "sha1-8h+sSQ2vHXZn/RgP6QdzicyUQrI=" + }, + "muri": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/muri/-/muri-1.1.0.tgz", + "integrity": "sha1-o6bXTmiogPQzokmnSWnLtmXMCt0=" + }, + "nan": { + "version": "1.8.4", + "resolved": "http://registry.npmjs.org/nan/-/nan-1.8.4.tgz", + "integrity": "sha1-PHa1OC6rM+RLdY0oE8qdkuk0LzQ=" + }, + "readable-stream": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.0.6.tgz", + "integrity": "sha512-9E1oLoOWfhSXHGv6QlwXJim7uNzd9EVlWK+21tCU9Ju/kR0/p2AZYPz4qSchgO8PlLIH4FpZYfzwS+rEksZjIg==", + "optional": true, + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "regexp-clone": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", + "integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=" + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "optional": true + }, + "sliced": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", + "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=" + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "optional": true + } + } +} From 29066d9b0e001c0aa57964759476378e1090aef3 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:43:29 +0800 Subject: [PATCH 02/10] module update --- node_modules/.bin/semver | 15 + node_modules/.bin/semver.cmd | 7 + .../node_modules => }/accepts/.npmignore | 0 .../node_modules => }/accepts/History.md | 0 .../node_modules => }/accepts/README.md | 0 .../node_modules => }/accepts/index.js | 0 .../node_modules => }/accepts/package.json | 77 +- node_modules/bson/HISTORY.md | 253 + node_modules/bson/{LICENSE => LICENSE.md} | 0 node_modules/bson/README.md | 193 +- node_modules/bson/bower.json | 25 + node_modules/bson/browser_build/bson.js | 22527 ++++++++++++---- node_modules/bson/browser_build/package.json | 2 +- node_modules/bson/index.js | 46 + node_modules/bson/lib/bson/binary.js | 208 +- node_modules/bson/lib/bson/bson.js | 1626 +- node_modules/bson/lib/bson/code.js | 10 +- node_modules/bson/lib/bson/db_ref.js | 16 +- node_modules/bson/lib/bson/decimal128.js | 818 + node_modules/bson/lib/bson/double.js | 8 +- node_modules/bson/lib/bson/float_parser.js | 63 +- node_modules/bson/lib/bson/int_32.js | 33 + node_modules/bson/lib/bson/long.js | 145 +- node_modules/bson/lib/bson/map.js | 128 + node_modules/bson/lib/bson/max_key.js | 8 +- node_modules/bson/lib/bson/min_key.js | 6 +- node_modules/bson/lib/bson/objectid.js | 285 +- .../bson/lib/bson/parser/calculate_size.js | 255 + .../bson/lib/bson/parser/deserializer.js | 780 + .../bson/lib/bson/parser/serializer.js | 1183 + node_modules/bson/lib/bson/parser/utils.js | 14 + node_modules/bson/lib/bson/regexp.js | 33 + node_modules/bson/lib/bson/symbol.js | 15 +- node_modules/bson/lib/bson/timestamp.js | 144 +- node_modules/bson/package.json | 64 +- .../node_modules => }/buffer-crc32/.npmignore | 0 .../buffer-crc32/.travis.yml | 0 .../node_modules => }/buffer-crc32/LICENSE | 0 .../node_modules => }/buffer-crc32/README.md | 0 .../node_modules => }/buffer-crc32/index.js | 0 .../buffer-crc32/package.json | 79 +- .../buffer-crc32/tests/crc.test.js | 0 .../LICENSE => circular-json/LICENSE.txt} | 2 +- node_modules/circular-json/README.md | 146 + .../circular-json/build/circular-json.js | 2 + .../circular-json/build/circular-json.max.js | 210 + .../circular-json/build/circular-json.node.js | 207 + node_modules/circular-json/package.json | 67 + .../circular-json/template/license.after | 2 + .../circular-json/template/license.before | 1 + .../cookie-signature/.npmignore | 0 .../cookie-signature/History.md | 0 .../cookie-signature/Makefile | 0 .../cookie-signature/Readme.md | 0 .../cookie-signature/index.js | 0 .../cookie-signature/package.json | 71 +- .../node_modules => }/cookie/.npmignore | 0 .../{express/node_modules => }/cookie/LICENSE | 0 .../node_modules => }/cookie/README.md | 0 .../node_modules => }/cookie/index.js | 0 .../node_modules => }/cookie/package.json | 83 +- .../node_modules => }/depd/.npmignore | 0 .../node_modules => }/depd/History.md | 0 .../{express/node_modules => }/depd/LICENSE | 0 .../{express/node_modules => }/depd/Readme.md | 0 .../{express/node_modules => }/depd/index.js | 0 .../node_modules => }/depd/package.json | 86 +- .../node_modules => }/ee-first/.npmignore | 0 .../mime-types => ee-first}/LICENSE | 0 .../node_modules => }/ee-first/README.md | 0 .../node_modules => }/ee-first/index.js | 0 .../node_modules => }/ee-first/package.json | 71 +- .../node_modules => }/ee-first/test.js | 0 .../node_modules => }/escape-html/.npmignore | 0 .../node_modules => }/escape-html/Makefile | 0 .../node_modules => }/escape-html/Readme.md | 0 .../escape-html/component.json | 0 .../node_modules => }/escape-html/index.js | 0 .../escape-html/package.json | 79 +- .../node_modules/mime-types/package.json | 68 - .../{debug/node_modules => }/ms/.npmignore | 0 .../{debug/node_modules => }/ms/README.md | 0 .../{debug/node_modules => }/ms/index.js | 0 .../{send/node_modules => }/ms/package.json | 69 +- .../node_modules/ee-first/package.json | 49 - .../send/node_modules/finished/package.json | 75 - .../send/node_modules/mime/package.json | 55 - .../send/node_modules/finished/HISTORY.md | 50 - .../send/node_modules/finished/README.md | 88 - .../send/node_modules/finished/index.js | 62 - .../finished/node_modules/ee-first/README.md | 5 - .../finished/node_modules/ee-first/index.js | 60 - .../finished/node_modules/ee-first/test.js | 60 - .../send/node_modules/mime/README.md | 66 - .../send/node_modules/mime/mime.js | 114 - .../send/node_modules/mime/test.js | 84 - .../send/node_modules/mime/types/mime.types | 1588 -- .../send/node_modules/mime/types/node.types | 77 - .../node_modules/mime-types/.npmignore | 14 - .../node_modules/mime-types/.travis.yml | 12 - .../type-is/node_modules/mime-types/Makefile | 9 - .../type-is/node_modules/mime-types/README.md | 101 - .../node_modules/mime-types/SOURCES.md | 17 - .../node_modules/mime-types/component.json | 16 - .../node_modules/mime-types/lib/custom.json | 27 - .../node_modules/mime-types/lib/index.js | 75 - .../node_modules/mime-types/lib/mime.json | 3317 --- .../node_modules/mime-types/lib/node.json | 55 - .../express/node_modules/vary/.npmignore | 3 - node_modules/express/package.json | 140 +- .../node_modules => }/finalhandler/.npmignore | 0 .../node_modules => }/finalhandler/HISTORY.md | 0 .../node_modules => }/finalhandler/README.md | 0 .../node_modules => }/finalhandler/index.js | 0 .../node_modules/debug/.jshintrc | 0 .../node_modules/debug/.npmignore | 0 .../node_modules/debug/History.md | 126 + .../node_modules/debug/Makefile | 0 .../node_modules/debug/Readme.md | 0 .../node_modules/debug/browser.js | 144 + .../node_modules/debug/component.json | 19 + .../finalhandler/node_modules/debug/debug.js | 197 + .../node_modules/debug/node.js | 0 .../node_modules/debug/package.json | 69 + .../node_modules/ms/.npmignore | 0 .../node_modules/ms/README.md | 0 .../node_modules/ms/index.js | 0 .../finalhandler/node_modules/ms/package.json | 49 + .../finalhandler/package.json | 77 +- .../media-typer => finished}/.npmignore | 0 .../node_modules => }/finished/HISTORY.md | 0 .../send/node_modules => }/finished/README.md | 0 .../send/node_modules => }/finished/index.js | 0 .../node_modules => }/finished/package.json | 79 +- .../node_modules => }/fresh/.npmignore | 0 .../node_modules => }/fresh/History.md | 0 .../{express/node_modules => }/fresh/Makefile | 0 .../node_modules => }/fresh/Readme.md | 0 .../{express/node_modules => }/fresh/index.js | 0 .../node_modules => }/fresh/package.json | 73 +- .../node_modules => }/ipaddr.js/.npmignore | 0 .../node_modules => }/ipaddr.js/Cakefile | 0 .../node_modules => }/ipaddr.js/LICENSE | 0 .../node_modules => }/ipaddr.js/README.md | 0 .../node_modules => }/ipaddr.js/ipaddr.min.js | 0 .../node_modules => }/ipaddr.js/lib/ipaddr.js | 0 .../node_modules => }/ipaddr.js/package.json | 82 +- .../ipaddr.js/src/ipaddr.coffee | 0 .../ipaddr.js/test/ipaddr.test.coffee | 0 .../finished => media-typer}/.npmignore | 0 .../node_modules => }/media-typer/HISTORY.md | 0 .../node_modules => }/media-typer/README.md | 0 .../node_modules => }/media-typer/index.js | 0 .../media-typer/package.json | 78 +- node_modules/memory-pager/.travis.yml | 4 + .../ee-first => memory-pager}/LICENSE | 3 +- node_modules/memory-pager/README.md | 65 + node_modules/memory-pager/index.js | 96 + node_modules/memory-pager/package.json | 52 + node_modules/memory-pager/test.js | 80 + .../merge-descriptors/.npmignore | 0 .../merge-descriptors/README.md | 0 .../merge-descriptors/component.json | 0 .../merge-descriptors/index.js | 0 .../merge-descriptors/package.json | 65 +- .../node_modules => }/methods/.npmignore | 0 .../node_modules => }/methods/History.md | 0 .../node_modules => }/methods/LICENSE | 0 .../node_modules => }/methods/Readme.md | 0 .../node_modules => }/methods/index.js | 0 .../node_modules => }/methods/package.json | 75 +- .../node_modules => }/methods/test/methods.js | 0 .../node_modules => }/mime-types/.npmignore | 0 .../node_modules => }/mime-types/.travis.yml | 0 .../ee-first => mime-types}/LICENSE | 0 .../node_modules => }/mime-types/Makefile | 0 .../node_modules => }/mime-types/README.md | 0 .../node_modules => }/mime-types/SOURCES.md | 0 .../mime-types/component.json | 0 .../mime-types/lib/custom.json | 0 .../node_modules => }/mime-types/lib/index.js | 0 .../mime-types/lib/mime.json | 0 .../mime-types/lib/node.json | 0 .../node_modules => }/mime-types/package.json | 78 +- .../send/node_modules => }/mime/LICENSE | 0 .../send/node_modules => }/mime/README.md | 0 .../send/node_modules => }/mime/mime.js | 0 .../send/node_modules => }/mime/package.json | 69 +- .../send/node_modules => }/mime/test.js | 0 .../node_modules => }/mime/types/mime.types | 0 .../node_modules => }/mime/types/node.types | 0 node_modules/mongodb-core/HISTORY.md | 1052 + node_modules/mongodb-core/LICENSE | 201 + node_modules/mongodb-core/README.md | 228 + node_modules/mongodb-core/index.js | 48 + .../lib/auth/defaultAuthProviders.js | 29 + node_modules/mongodb-core/lib/auth/gssapi.js | 381 + node_modules/mongodb-core/lib/auth/mongocr.js | 214 + node_modules/mongodb-core/lib/auth/plain.js | 183 + node_modules/mongodb-core/lib/auth/scram.js | 442 + node_modules/mongodb-core/lib/auth/sspi.js | 262 + node_modules/mongodb-core/lib/auth/x509.js | 179 + .../mongodb-core/lib/connection/apm.js | 229 + .../lib/connection/command_result.js | 34 + .../mongodb-core/lib/connection/commands.js | 549 + .../mongodb-core/lib/connection/connection.js | 805 + .../mongodb-core/lib/connection/logger.js | 246 + .../mongodb-core/lib/connection/pool.js | 1657 ++ .../mongodb-core/lib/connection/utils.js | 113 + node_modules/mongodb-core/lib/cursor.js | 836 + node_modules/mongodb-core/lib/error.js | 146 + node_modules/mongodb-core/lib/sdam/cursor.js | 749 + .../mongodb-core/lib/sdam/monitoring.js | 217 + node_modules/mongodb-core/lib/sdam/server.js | 413 + .../lib/sdam/server_description.js | 141 + .../mongodb-core/lib/sdam/server_selectors.js | 206 + .../mongodb-core/lib/sdam/topology.js | 666 + .../lib/sdam/topology_description.js | 364 + node_modules/mongodb-core/lib/sessions.js | 459 + .../mongodb-core/lib/tools/smoke_plugin.js | 61 + .../mongodb-core/lib/topologies/mongos.js | 1506 ++ .../lib/topologies/read_preference.js | 193 + .../mongodb-core/lib/topologies/replset.js | 1722 ++ .../lib/topologies/replset_state.js | 1099 + .../mongodb-core/lib/topologies/server.js | 1143 + .../mongodb-core/lib/topologies/shared.js | 434 + node_modules/mongodb-core/lib/transactions.js | 134 + node_modules/mongodb-core/lib/uri_parser.js | 546 + node_modules/mongodb-core/lib/utils.js | 97 + .../lib/wireprotocol/2_6_support.js | 368 + .../lib/wireprotocol/3_2_support.js | 682 + .../lib/wireprotocol/compression.js | 73 + .../mongodb-core/lib/wireprotocol/shared.js | 55 + node_modules/mongodb-core/package.json | 90 + node_modules/mongodb/HISTORY.md | 2175 ++ node_modules/mongodb/LICENSE.md | 201 + node_modules/mongodb/Readme.md | 635 +- node_modules/mongodb/index.js | 68 +- node_modules/mongodb/lib/admin.js | 293 + .../mongodb/lib/aggregation_cursor.js | 407 + node_modules/mongodb/lib/apm.js | 31 + node_modules/mongodb/lib/authenticate.js | 136 + node_modules/mongodb/lib/bulk/common.js | 1105 + node_modules/mongodb/lib/bulk/ordered.js | 178 + node_modules/mongodb/lib/bulk/unordered.js | 202 + node_modules/mongodb/lib/change_stream.js | 455 + node_modules/mongodb/lib/collection.js | 2087 ++ node_modules/mongodb/lib/command_cursor.js | 334 + node_modules/mongodb/lib/constants.js | 10 + node_modules/mongodb/lib/cursor.js | 1152 + node_modules/mongodb/lib/db.js | 985 + node_modules/mongodb/lib/error.js | 43 + .../mongodb/lib/gridfs-stream/download.js | 415 + .../mongodb/lib/gridfs-stream/index.js | 358 + .../mongodb/lib/gridfs-stream/upload.js | 538 + node_modules/mongodb/lib/gridfs/chunk.js | 236 + node_modules/mongodb/lib/gridfs/grid_store.js | 1907 ++ node_modules/mongodb/lib/mongo_client.js | 472 + .../mongodb/lib/operations/admin_ops.js | 62 + .../mongodb/lib/operations/collection_ops.js | 1479 + .../mongodb/lib/operations/cursor_ops.js | 242 + node_modules/mongodb/lib/operations/db_ops.js | 986 + .../lib/operations/mongo_client_ops.js | 642 + node_modules/mongodb/lib/topologies/mongos.js | 452 + .../mongodb/lib/topologies/replset.js | 497 + node_modules/mongodb/lib/topologies/server.js | 455 + .../mongodb/lib/topologies/topology_base.js | 446 + node_modules/mongodb/lib/url_parser.js | 622 + node_modules/mongodb/lib/utils.js | 720 + node_modules/mongodb/package.json | 278 +- .../node_modules}/bson/.travis.yml | 0 .../{ => mongoose/node_modules}/bson/HISTORY | 0 .../node_modules/bson}/LICENSE | 0 .../{ => mongoose/node_modules}/bson/Makefile | 0 .../mongoose/node_modules/bson/README.md | 69 + .../node_modules}/bson/binding.gyp | 0 .../node_modules/bson/browser_build/bson.js | 4843 ++++ .../bson/browser_build/package.json | 8 + .../node_modules}/bson/build_browser.js | 0 .../node_modules}/bson/builderror.log | 2 +- .../node_modules}/bson/ext/Makefile | 0 .../node_modules}/bson/ext/bson.cc | 0 .../node_modules}/bson/ext/bson.h | 0 .../node_modules}/bson/ext/index.js | 4 +- .../bson/ext/win32/ia32/bson.node | Bin .../bson/ext/win32/x64/bson.node | Bin .../node_modules}/bson/ext/wscript | 0 .../node_modules/bson/lib/bson/binary.js | 344 + .../bson/lib/bson/binary_parser.js | 0 .../node_modules/bson/lib/bson/bson.js | 1573 ++ .../node_modules}/bson/lib/bson/bson_new.js | 0 .../node_modules/bson/lib/bson/code.js | 24 + .../node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 121 + .../node_modules}/bson/lib/bson/index.js | 0 .../node_modules/bson/lib/bson/long.js | 856 + .../node_modules/bson/lib/bson/max_key.js | 14 + .../node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 274 + .../node_modules/bson/lib/bson/symbol.js | 47 + .../node_modules/bson/lib/bson/timestamp.js | 856 + .../mongoose/node_modules/bson/package.json | 77 + .../node_modules}/bson/tools/gleak.js | 0 .../bson/tools/jasmine-1.1.0/MIT.LICENSE | 0 .../bson/tools/jasmine-1.1.0/jasmine-html.js | 0 .../bson/tools/jasmine-1.1.0/jasmine.css | 0 .../bson/tools/jasmine-1.1.0/jasmine.js | 0 .../tools/jasmine-1.1.0/jasmine_favicon.png | Bin .../node_modules}/mongodb/.gitmodules | 0 .../node_modules}/mongodb/.travis.yml | 0 .../node_modules}/mongodb/CONTRIBUTING.md | 0 .../node_modules}/mongodb/HISTORY | 0 .../mongoose/node_modules/mongodb/LICENSE | 201 + .../node_modules}/mongodb/Makefile | 0 .../mongoose/node_modules/mongodb/Readme.md | 418 + .../mongoose/node_modules/mongodb/index.js | 1 + .../mongodb/lib/mongodb/admin.js | 0 .../mongodb/lib/mongodb/aggregation_cursor.js | 0 .../mongodb/lib/mongodb/auth/mongodb_cr.js | 0 .../lib/mongodb/auth/mongodb_gssapi.js | 0 .../mongodb/lib/mongodb/auth/mongodb_plain.js | 0 .../mongodb/lib/mongodb/auth/mongodb_scram.js | 0 .../mongodb/lib/mongodb/auth/mongodb_sspi.js | 0 .../mongodb/lib/mongodb/auth/mongodb_x509.js | 0 .../mongodb/lib/mongodb/collection.js | 0 .../lib/mongodb/collection/aggregation.js | 0 .../lib/mongodb/collection/batch/common.js | 0 .../lib/mongodb/collection/batch/ordered.js | 0 .../lib/mongodb/collection/batch/unordered.js | 0 .../lib/mongodb/collection/commands.js | 0 .../mongodb/lib/mongodb/collection/core.js | 0 .../mongodb/lib/mongodb/collection/geo.js | 0 .../mongodb/lib/mongodb/collection/index.js | 0 .../mongodb/lib/mongodb/collection/query.js | 0 .../mongodb/lib/mongodb/collection/shared.js | 0 .../mongodb/lib/mongodb/command_cursor.js | 0 .../lib/mongodb/commands/base_command.js | 0 .../lib/mongodb/commands/db_command.js | 0 .../lib/mongodb/commands/delete_command.js | 0 .../lib/mongodb/commands/get_more_command.js | 0 .../lib/mongodb/commands/insert_command.js | 0 .../mongodb/commands/kill_cursor_command.js | 0 .../lib/mongodb/commands/query_command.js | 0 .../lib/mongodb/commands/update_command.js | 0 .../mongodb/lib/mongodb/connection/base.js | 0 .../lib/mongodb/connection/connection.js | 0 .../lib/mongodb/connection/connection_pool.js | 0 .../mongodb/connection/connection_utils.js | 0 .../mongodb/lib/mongodb/connection/mongos.js | 0 .../lib/mongodb/connection/read_preference.js | 0 .../lib/mongodb/connection/repl_set/ha.js | 0 .../mongodb/connection/repl_set/options.js | 0 .../mongodb/connection/repl_set/repl_set.js | 0 .../connection/repl_set/repl_set_state.js | 0 .../repl_set/strategies/ping_strategy.js | 0 .../strategies/statistics_strategy.js | 0 .../mongodb/lib/mongodb/connection/server.js | 0 .../mongodb/connection/server_capabilities.js | 0 .../lib/mongodb/connection/url_parser.js | 0 .../mongodb/lib/mongodb/cursor.js | 0 .../mongodb/lib/mongodb/cursorstream.js | 0 .../node_modules}/mongodb/lib/mongodb/db.js | 0 .../mongodb/lib/mongodb/gridfs/chunk.js | 0 .../mongodb/lib/mongodb/gridfs/grid.js | 0 .../mongodb/lib/mongodb/gridfs/gridstore.js | 0 .../mongodb/lib/mongodb/gridfs/readstream.js | 0 .../mongodb/lib/mongodb/index.js | 0 .../mongodb/lib/mongodb/mongo_client.js | 0 .../lib/mongodb/responses/mongo_reply.js | 0 .../mongodb/lib/mongodb/scope.js | 0 .../mongodb/lib/mongodb/utils.js | 0 .../node_modules/mongodb/package.json | 255 + .../node_modules}/mongodb/repo_node_418.js | 0 .../node_modules}/mongodb/wercker.yml | 0 .../node_modules => }/negotiator/.npmignore | 0 .../node_modules => }/negotiator/LICENSE | 0 .../negotiator/lib/charset.js | 0 .../negotiator/lib/encoding.js | 0 .../negotiator/lib/language.js | 0 .../negotiator/lib/mediaType.js | 0 .../negotiator/lib/negotiator.js | 0 .../node_modules => }/negotiator/package.json | 93 +- .../node_modules => }/negotiator/readme.md | 0 .../node_modules => }/parseurl/.npmignore | 0 .../node_modules => }/parseurl/README.md | 0 .../node_modules => }/parseurl/index.js | 0 .../node_modules => }/parseurl/package.json | 61 +- .../path-to-regexp/.npmignore | 0 .../path-to-regexp/History.md | 0 .../path-to-regexp/Readme.md | 0 .../path-to-regexp/component.json | 0 .../node_modules => }/path-to-regexp/index.js | 0 .../path-to-regexp/package.json | 77 +- .../node_modules => }/path-to-regexp/test.js | 0 .../node_modules => }/proxy-addr/.npmignore | 0 .../node_modules => }/proxy-addr/History.md | 0 .../node_modules => }/proxy-addr/LICENSE | 0 .../node_modules => }/proxy-addr/README.md | 0 .../node_modules => }/proxy-addr/index.js | 0 .../node_modules => }/proxy-addr/package.json | 87 +- .../{express/node_modules => }/qs/.gitmodules | 0 .../{express/node_modules => }/qs/.npmignore | 0 .../{express/node_modules => }/qs/Readme.md | 0 .../{express/node_modules => }/qs/index.js | 0 .../node_modules => }/qs/package.json | 82 +- .../node_modules => }/range-parser/.npmignore | 0 .../node_modules => }/range-parser/History.md | 0 .../node_modules => }/range-parser/Makefile | 0 .../node_modules => }/range-parser/Readme.md | 0 .../node_modules => }/range-parser/index.js | 0 .../range-parser/package.json | 72 +- node_modules/require_optional/.npmignore | 33 + node_modules/require_optional/.travis.yml | 9 + node_modules/require_optional/HISTORY.md | 7 + node_modules/require_optional/LICENSE | 201 + node_modules/require_optional/README.md | 2 + node_modules/require_optional/index.js | 128 + node_modules/require_optional/package.json | 67 + .../require_optional/test/nestedTest/index.js | 8 + .../test/nestedTest/package.json | 11 + .../test/require_optional_tests.js | 59 + node_modules/resolve-from/index.js | 23 + node_modules/resolve-from/license | 21 + node_modules/resolve-from/package.json | 66 + node_modules/resolve-from/readme.md | 58 + node_modules/saslprep/.editorconfig | 10 + node_modules/saslprep/.eslintrc | 17 + node_modules/saslprep/.gitattributes | 1 + node_modules/saslprep/.travis.yml | 5 + node_modules/saslprep/LICENSE | 22 + node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes node_modules/saslprep/generate-code-points.js | 48 + node_modules/saslprep/index.js | 120 + node_modules/saslprep/lib/code-points.js | 996 + .../saslprep/lib/memory-code-points.js | 34 + node_modules/saslprep/lib/util.js | 15 + node_modules/saslprep/package.json | 66 + node_modules/saslprep/readme.md | 31 + node_modules/saslprep/test/index.js | 70 + node_modules/saslprep/test/util.js | 15 + node_modules/semver/LICENSE | 15 + node_modules/semver/README.md | 399 + node_modules/semver/bin/semver | 153 + node_modules/semver/package.json | 54 + node_modules/semver/range.bnf | 16 + node_modules/semver/semver.js | 1352 + .../node_modules => }/send/.npmignore | 0 .../node_modules => }/send/History.md | 0 .../{express/node_modules => }/send/Readme.md | 0 .../{express/node_modules => }/send/index.js | 0 .../node_modules => }/send/lib/send.js | 0 .../node_modules => }/send/lib/utils.js | 0 .../send/node_modules/debug/.jshintrc | 3 + .../send/node_modules/debug/.npmignore | 6 + .../send/node_modules/debug/History.md | 126 + node_modules/send/node_modules/debug/Makefile | 33 + .../send/node_modules/debug/Readme.md | 153 + .../send/node_modules/debug/browser.js | 144 + .../send/node_modules/debug/component.json | 19 + node_modules/send/node_modules/debug/debug.js | 197 + node_modules/send/node_modules/debug/node.js | 129 + .../send/node_modules/debug/package.json | 69 + .../send/node_modules/ms/.npmignore | 0 .../send/node_modules/ms/README.md | 0 .../send/node_modules/ms/index.js | 0 .../node_modules/ms/package.json | 70 +- .../node_modules => }/send/package.json | 89 +- .../node_modules => }/serve-static/.npmignore | 0 .../node_modules => }/serve-static/History.md | 0 .../node_modules => }/serve-static/LICENSE | 0 .../node_modules => }/serve-static/Readme.md | 0 .../node_modules => }/serve-static/index.js | 0 .../serve-static/node_modules/debug/.jshintrc | 3 + .../node_modules/debug/.npmignore | 6 + .../node_modules/debug/History.md | 0 .../serve-static/node_modules/debug/Makefile | 33 + .../serve-static/node_modules/debug/Readme.md | 153 + .../node_modules/debug/browser.js | 0 .../node_modules/debug/component.json | 0 .../node_modules/debug/debug.js | 0 .../serve-static/node_modules/debug/node.js | 129 + .../node_modules/debug/package.json | 89 +- .../serve-static/node_modules/ms/.npmignore | 5 + .../serve-static/node_modules/ms/README.md | 33 + .../serve-static/node_modules/ms/index.js | 111 + .../node_modules/ms/package.json | 71 +- .../node_modules/parseurl/.npmignore | 0 .../node_modules/parseurl/HISTORY.md | 0 .../node_modules/parseurl/README.md | 0 .../node_modules/parseurl/index.js | 0 .../node_modules/parseurl/package.json | 59 +- .../serve-static/node_modules/send/.npmignore | 0 .../serve-static/node_modules/send/History.md | 0 .../serve-static/node_modules/send/Readme.md | 0 .../serve-static/node_modules/send/index.js | 0 .../node_modules/send/lib/send.js | 0 .../node_modules/send/lib/utils.js | 0 .../node_modules/send/package.json | 89 +- .../serve-static/package.json | 84 +- .../ee-first => sparse-bitfield}/.npmignore | 1 - node_modules/sparse-bitfield/.travis.yml | 6 + .../mime-types => sparse-bitfield}/LICENSE | 3 +- node_modules/sparse-bitfield/README.md | 62 + node_modules/sparse-bitfield/index.js | 95 + node_modules/sparse-bitfield/package.json | 55 + node_modules/sparse-bitfield/test.js | 79 + .../finished => type-is}/.npmignore | 0 .../node_modules => }/type-is/HISTORY.md | 0 .../node_modules => }/type-is/README.md | 0 .../node_modules => }/type-is/index.js | 0 .../node_modules => }/type-is/package.json | 79 +- .../node_modules => }/utils-merge/.travis.yml | 0 .../node_modules => }/utils-merge/LICENSE | 0 .../node_modules => }/utils-merge/README.md | 0 .../node_modules => }/utils-merge/index.js | 0 .../utils-merge/package.json | 92 +- .../node_modules/type-is => vary}/.npmignore | 0 .../node_modules => }/vary/History.md | 0 .../{express/node_modules => }/vary/LICENSE | 0 .../{express/node_modules => }/vary/README.md | 0 .../{express/node_modules => }/vary/index.js | 0 .../node_modules => }/vary/package.json | 87 +- 523 files changed, 81386 insertions(+), 14331 deletions(-) create mode 100644 node_modules/.bin/semver create mode 100644 node_modules/.bin/semver.cmd rename node_modules/{express/node_modules => }/accepts/.npmignore (100%) rename node_modules/{express/node_modules => }/accepts/History.md (100%) rename node_modules/{express/node_modules => }/accepts/README.md (100%) rename node_modules/{express/node_modules => }/accepts/index.js (100%) rename node_modules/{express/node_modules => }/accepts/package.json (74%) create mode 100644 node_modules/bson/HISTORY.md rename node_modules/bson/{LICENSE => LICENSE.md} (100%) create mode 100644 node_modules/bson/bower.json create mode 100644 node_modules/bson/index.js create mode 100644 node_modules/bson/lib/bson/decimal128.js create mode 100644 node_modules/bson/lib/bson/int_32.js create mode 100644 node_modules/bson/lib/bson/map.js create mode 100644 node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 node_modules/bson/lib/bson/parser/serializer.js create mode 100644 node_modules/bson/lib/bson/parser/utils.js create mode 100644 node_modules/bson/lib/bson/regexp.js rename node_modules/{express/node_modules => }/buffer-crc32/.npmignore (100%) rename node_modules/{express/node_modules => }/buffer-crc32/.travis.yml (100%) rename node_modules/{express/node_modules => }/buffer-crc32/LICENSE (100%) rename node_modules/{express/node_modules => }/buffer-crc32/README.md (100%) rename node_modules/{express/node_modules => }/buffer-crc32/index.js (100%) rename node_modules/{express/node_modules => }/buffer-crc32/package.json (70%) rename node_modules/{express/node_modules => }/buffer-crc32/tests/crc.test.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules/mime/LICENSE => circular-json/LICENSE.txt} (94%) create mode 100644 node_modules/circular-json/README.md create mode 100644 node_modules/circular-json/build/circular-json.js create mode 100644 node_modules/circular-json/build/circular-json.max.js create mode 100644 node_modules/circular-json/build/circular-json.node.js create mode 100644 node_modules/circular-json/package.json create mode 100644 node_modules/circular-json/template/license.after create mode 100644 node_modules/circular-json/template/license.before rename node_modules/{express/node_modules => }/cookie-signature/.npmignore (100%) rename node_modules/{express/node_modules => }/cookie-signature/History.md (100%) rename node_modules/{express/node_modules => }/cookie-signature/Makefile (100%) rename node_modules/{express/node_modules => }/cookie-signature/Readme.md (100%) rename node_modules/{express/node_modules => }/cookie-signature/index.js (100%) rename node_modules/{express/node_modules => }/cookie-signature/package.json (62%) rename node_modules/{express/node_modules => }/cookie/.npmignore (100%) rename node_modules/{express/node_modules => }/cookie/LICENSE (100%) rename node_modules/{express/node_modules => }/cookie/README.md (100%) rename node_modules/{express/node_modules => }/cookie/index.js (100%) rename node_modules/{express/node_modules => }/cookie/package.json (67%) rename node_modules/{express/node_modules => }/depd/.npmignore (100%) rename node_modules/{express/node_modules => }/depd/History.md (100%) rename node_modules/{express/node_modules => }/depd/LICENSE (100%) rename node_modules/{express/node_modules => }/depd/Readme.md (100%) rename node_modules/{express/node_modules => }/depd/index.js (100%) rename node_modules/{express/node_modules => }/depd/package.json (66%) rename node_modules/{express/node_modules/send/node_modules/finished/node_modules => }/ee-first/.npmignore (100%) rename node_modules/{express/node_modules/accepts/node_modules/mime-types => ee-first}/LICENSE (100%) rename node_modules/{express/node_modules/send/node_modules/finished/node_modules => }/ee-first/README.md (100%) rename node_modules/{express/node_modules/send/node_modules/finished/node_modules => }/ee-first/index.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules => }/ee-first/package.json (65%) rename node_modules/{express/node_modules/send/node_modules/finished/node_modules => }/ee-first/test.js (100%) rename node_modules/{express/node_modules => }/escape-html/.npmignore (100%) rename node_modules/{express/node_modules => }/escape-html/Makefile (100%) rename node_modules/{express/node_modules => }/escape-html/Readme.md (100%) rename node_modules/{express/node_modules => }/escape-html/component.json (100%) rename node_modules/{express/node_modules => }/escape-html/index.js (100%) rename node_modules/{express/node_modules => }/escape-html/package.json (57%) delete mode 100644 node_modules/express/node_modules/accepts/node_modules/mime-types/package.json rename node_modules/express/node_modules/{debug/node_modules => }/ms/.npmignore (100%) rename node_modules/express/node_modules/{debug/node_modules => }/ms/README.md (100%) rename node_modules/express/node_modules/{debug/node_modules => }/ms/index.js (100%) rename node_modules/express/node_modules/{send/node_modules => }/ms/package.json (55%) delete mode 100644 node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/package.json delete mode 100644 node_modules/express/node_modules/send/node_modules/finished/package.json delete mode 100644 node_modules/express/node_modules/send/node_modules/mime/package.json delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/HISTORY.md delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/README.md delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/index.js delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/README.md delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/index.js delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/test.js delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/README.md delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/mime.js delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/test.js delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/mime.types delete mode 100644 node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/node.types delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/.npmignore delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/.travis.yml delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/Makefile delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/README.md delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/SOURCES.md delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/component.json delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/lib/custom.json delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/lib/index.js delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/lib/mime.json delete mode 100644 node_modules/express/node_modules/type-is/node_modules/mime-types/lib/node.json delete mode 100644 node_modules/express/node_modules/vary/.npmignore rename node_modules/{express/node_modules => }/finalhandler/.npmignore (100%) rename node_modules/{express/node_modules => }/finalhandler/HISTORY.md (100%) rename node_modules/{express/node_modules => }/finalhandler/README.md (100%) rename node_modules/{express/node_modules => }/finalhandler/index.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send => finalhandler}/node_modules/debug/.jshintrc (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send => finalhandler}/node_modules/debug/.npmignore (100%) create mode 100644 node_modules/finalhandler/node_modules/debug/History.md rename node_modules/{express/node_modules/serve-static/node_modules/send => finalhandler}/node_modules/debug/Makefile (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send => finalhandler}/node_modules/debug/Readme.md (100%) create mode 100644 node_modules/finalhandler/node_modules/debug/browser.js create mode 100644 node_modules/finalhandler/node_modules/debug/component.json create mode 100644 node_modules/finalhandler/node_modules/debug/debug.js rename node_modules/{express/node_modules/serve-static/node_modules/send => finalhandler}/node_modules/debug/node.js (100%) create mode 100644 node_modules/finalhandler/node_modules/debug/package.json rename node_modules/{express/node_modules/send => finalhandler}/node_modules/ms/.npmignore (100%) rename node_modules/{express/node_modules/send => finalhandler}/node_modules/ms/README.md (100%) rename node_modules/{express/node_modules/send => finalhandler}/node_modules/ms/index.js (100%) create mode 100644 node_modules/finalhandler/node_modules/ms/package.json rename node_modules/{express/node_modules => }/finalhandler/package.json (70%) rename node_modules/{express/node_modules/media-typer => finished}/.npmignore (100%) rename node_modules/{express/node_modules/send/node_modules => }/finished/HISTORY.md (100%) rename node_modules/{express/node_modules/send/node_modules => }/finished/README.md (100%) rename node_modules/{express/node_modules/send/node_modules => }/finished/index.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules => }/finished/package.json (74%) rename node_modules/{express/node_modules => }/fresh/.npmignore (100%) rename node_modules/{express/node_modules => }/fresh/History.md (100%) rename node_modules/{express/node_modules => }/fresh/Makefile (100%) rename node_modules/{express/node_modules => }/fresh/Readme.md (100%) rename node_modules/{express/node_modules => }/fresh/index.js (100%) rename node_modules/{express/node_modules => }/fresh/package.json (64%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/.npmignore (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/Cakefile (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/LICENSE (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/README.md (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/ipaddr.min.js (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/lib/ipaddr.js (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/package.json (63%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/src/ipaddr.coffee (100%) rename node_modules/{express/node_modules/proxy-addr/node_modules => }/ipaddr.js/test/ipaddr.test.coffee (100%) rename node_modules/{express/node_modules/send/node_modules/finished => media-typer}/.npmignore (100%) rename node_modules/{express/node_modules => }/media-typer/HISTORY.md (100%) rename node_modules/{express/node_modules => }/media-typer/README.md (100%) rename node_modules/{express/node_modules => }/media-typer/index.js (100%) rename node_modules/{express/node_modules => }/media-typer/package.json (64%) create mode 100644 node_modules/memory-pager/.travis.yml rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first => memory-pager}/LICENSE (95%) create mode 100644 node_modules/memory-pager/README.md create mode 100644 node_modules/memory-pager/index.js create mode 100644 node_modules/memory-pager/package.json create mode 100644 node_modules/memory-pager/test.js rename node_modules/{express/node_modules => }/merge-descriptors/.npmignore (100%) rename node_modules/{express/node_modules => }/merge-descriptors/README.md (100%) rename node_modules/{express/node_modules => }/merge-descriptors/component.json (100%) rename node_modules/{express/node_modules => }/merge-descriptors/index.js (100%) rename node_modules/{express/node_modules => }/merge-descriptors/package.json (60%) rename node_modules/{express/node_modules => }/methods/.npmignore (100%) rename node_modules/{express/node_modules => }/methods/History.md (100%) rename node_modules/{express/node_modules => }/methods/LICENSE (100%) rename node_modules/{express/node_modules => }/methods/Readme.md (100%) rename node_modules/{express/node_modules => }/methods/index.js (100%) rename node_modules/{express/node_modules => }/methods/package.json (66%) rename node_modules/{express/node_modules => }/methods/test/methods.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/.npmignore (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/.travis.yml (100%) rename node_modules/{express/node_modules/send/node_modules/finished/node_modules/ee-first => mime-types}/LICENSE (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/Makefile (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/README.md (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/SOURCES.md (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/component.json (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/lib/custom.json (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/lib/index.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/lib/mime.json (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/mime-types/lib/node.json (100%) rename node_modules/{express/node_modules/type-is/node_modules => }/mime-types/package.json (66%) rename node_modules/{express/node_modules/send/node_modules => }/mime/LICENSE (100%) rename node_modules/{express/node_modules/send/node_modules => }/mime/README.md (100%) rename node_modules/{express/node_modules/send/node_modules => }/mime/mime.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules => }/mime/package.json (63%) rename node_modules/{express/node_modules/send/node_modules => }/mime/test.js (100%) rename node_modules/{express/node_modules/send/node_modules => }/mime/types/mime.types (100%) rename node_modules/{express/node_modules/send/node_modules => }/mime/types/node.types (100%) create mode 100644 node_modules/mongodb-core/HISTORY.md create mode 100644 node_modules/mongodb-core/LICENSE create mode 100644 node_modules/mongodb-core/README.md create mode 100644 node_modules/mongodb-core/index.js create mode 100644 node_modules/mongodb-core/lib/auth/defaultAuthProviders.js create mode 100644 node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 node_modules/mongodb-core/lib/auth/plain.js create mode 100644 node_modules/mongodb-core/lib/auth/scram.js create mode 100644 node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 node_modules/mongodb-core/lib/auth/x509.js create mode 100644 node_modules/mongodb-core/lib/connection/apm.js create mode 100644 node_modules/mongodb-core/lib/connection/command_result.js create mode 100644 node_modules/mongodb-core/lib/connection/commands.js create mode 100644 node_modules/mongodb-core/lib/connection/connection.js create mode 100644 node_modules/mongodb-core/lib/connection/logger.js create mode 100644 node_modules/mongodb-core/lib/connection/pool.js create mode 100644 node_modules/mongodb-core/lib/connection/utils.js create mode 100644 node_modules/mongodb-core/lib/cursor.js create mode 100644 node_modules/mongodb-core/lib/error.js create mode 100644 node_modules/mongodb-core/lib/sdam/cursor.js create mode 100644 node_modules/mongodb-core/lib/sdam/monitoring.js create mode 100644 node_modules/mongodb-core/lib/sdam/server.js create mode 100644 node_modules/mongodb-core/lib/sdam/server_description.js create mode 100644 node_modules/mongodb-core/lib/sdam/server_selectors.js create mode 100644 node_modules/mongodb-core/lib/sdam/topology.js create mode 100644 node_modules/mongodb-core/lib/sdam/topology_description.js create mode 100644 node_modules/mongodb-core/lib/sessions.js create mode 100644 node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 node_modules/mongodb-core/lib/topologies/server.js create mode 100644 node_modules/mongodb-core/lib/topologies/shared.js create mode 100644 node_modules/mongodb-core/lib/transactions.js create mode 100644 node_modules/mongodb-core/lib/uri_parser.js create mode 100644 node_modules/mongodb-core/lib/utils.js create mode 100644 node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 node_modules/mongodb-core/lib/wireprotocol/3_2_support.js create mode 100644 node_modules/mongodb-core/lib/wireprotocol/compression.js create mode 100644 node_modules/mongodb-core/lib/wireprotocol/shared.js create mode 100644 node_modules/mongodb-core/package.json create mode 100644 node_modules/mongodb/HISTORY.md create mode 100644 node_modules/mongodb/LICENSE.md create mode 100644 node_modules/mongodb/lib/admin.js create mode 100644 node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 node_modules/mongodb/lib/apm.js create mode 100644 node_modules/mongodb/lib/authenticate.js create mode 100644 node_modules/mongodb/lib/bulk/common.js create mode 100644 node_modules/mongodb/lib/bulk/ordered.js create mode 100644 node_modules/mongodb/lib/bulk/unordered.js create mode 100644 node_modules/mongodb/lib/change_stream.js create mode 100644 node_modules/mongodb/lib/collection.js create mode 100644 node_modules/mongodb/lib/command_cursor.js create mode 100644 node_modules/mongodb/lib/constants.js create mode 100644 node_modules/mongodb/lib/cursor.js create mode 100644 node_modules/mongodb/lib/db.js create mode 100644 node_modules/mongodb/lib/error.js create mode 100644 node_modules/mongodb/lib/gridfs-stream/download.js create mode 100644 node_modules/mongodb/lib/gridfs-stream/index.js create mode 100644 node_modules/mongodb/lib/gridfs-stream/upload.js create mode 100644 node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 node_modules/mongodb/lib/mongo_client.js create mode 100644 node_modules/mongodb/lib/operations/admin_ops.js create mode 100644 node_modules/mongodb/lib/operations/collection_ops.js create mode 100644 node_modules/mongodb/lib/operations/cursor_ops.js create mode 100644 node_modules/mongodb/lib/operations/db_ops.js create mode 100644 node_modules/mongodb/lib/operations/mongo_client_ops.js create mode 100644 node_modules/mongodb/lib/topologies/mongos.js create mode 100644 node_modules/mongodb/lib/topologies/replset.js create mode 100644 node_modules/mongodb/lib/topologies/server.js create mode 100644 node_modules/mongodb/lib/topologies/topology_base.js create mode 100644 node_modules/mongodb/lib/url_parser.js create mode 100644 node_modules/mongodb/lib/utils.js rename node_modules/{ => mongoose/node_modules}/bson/.travis.yml (100%) rename node_modules/{ => mongoose/node_modules}/bson/HISTORY (100%) rename node_modules/{mongodb => mongoose/node_modules/bson}/LICENSE (100%) rename node_modules/{ => mongoose/node_modules}/bson/Makefile (100%) create mode 100644 node_modules/mongoose/node_modules/bson/README.md rename node_modules/{ => mongoose/node_modules}/bson/binding.gyp (100%) create mode 100644 node_modules/mongoose/node_modules/bson/browser_build/bson.js create mode 100644 node_modules/mongoose/node_modules/bson/browser_build/package.json rename node_modules/{ => mongoose/node_modules}/bson/build_browser.js (100%) rename node_modules/{ => mongoose/node_modules}/bson/builderror.log (91%) rename node_modules/{ => mongoose/node_modules}/bson/ext/Makefile (100%) rename node_modules/{ => mongoose/node_modules}/bson/ext/bson.cc (100%) rename node_modules/{ => mongoose/node_modules}/bson/ext/bson.h (100%) rename node_modules/{ => mongoose/node_modules}/bson/ext/index.js (94%) rename node_modules/{ => mongoose/node_modules}/bson/ext/win32/ia32/bson.node (100%) rename node_modules/{ => mongoose/node_modules}/bson/ext/win32/x64/bson.node (100%) rename node_modules/{ => mongoose/node_modules}/bson/ext/wscript (100%) create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/binary.js rename node_modules/{ => mongoose/node_modules}/bson/lib/bson/binary_parser.js (100%) create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/bson.js rename node_modules/{ => mongoose/node_modules}/bson/lib/bson/bson_new.js (100%) create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/code.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/double.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js rename node_modules/{ => mongoose/node_modules}/bson/lib/bson/index.js (100%) create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/long.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/max_key.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/min_key.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/objectid.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/symbol.js create mode 100644 node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js create mode 100644 node_modules/mongoose/node_modules/bson/package.json rename node_modules/{ => mongoose/node_modules}/bson/tools/gleak.js (100%) rename node_modules/{ => mongoose/node_modules}/bson/tools/jasmine-1.1.0/MIT.LICENSE (100%) rename node_modules/{ => mongoose/node_modules}/bson/tools/jasmine-1.1.0/jasmine-html.js (100%) rename node_modules/{ => mongoose/node_modules}/bson/tools/jasmine-1.1.0/jasmine.css (100%) rename node_modules/{ => mongoose/node_modules}/bson/tools/jasmine-1.1.0/jasmine.js (100%) rename node_modules/{ => mongoose/node_modules}/bson/tools/jasmine-1.1.0/jasmine_favicon.png (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/.gitmodules (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/.travis.yml (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/CONTRIBUTING.md (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/HISTORY (100%) create mode 100644 node_modules/mongoose/node_modules/mongodb/LICENSE rename node_modules/{ => mongoose/node_modules}/mongodb/Makefile (100%) create mode 100644 node_modules/mongoose/node_modules/mongodb/Readme.md create mode 100644 node_modules/mongoose/node_modules/mongodb/index.js rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/admin.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/aggregation_cursor.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_cr.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_gssapi.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_plain.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_scram.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_sspi.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/auth/mongodb_x509.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/aggregation.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/batch/common.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/batch/ordered.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/batch/unordered.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/commands.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/core.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/geo.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/index.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/query.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/collection/shared.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/command_cursor.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/base_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/db_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/delete_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/get_more_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/insert_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/kill_cursor_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/query_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/commands/update_command.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/base.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/connection.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/connection_pool.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/connection_utils.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/mongos.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/read_preference.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/ha.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/options.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/repl_set.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/server.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/server_capabilities.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/connection/url_parser.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/cursor.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/cursorstream.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/db.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/gridfs/chunk.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/gridfs/grid.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/gridfs/gridstore.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/gridfs/readstream.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/index.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/mongo_client.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/responses/mongo_reply.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/scope.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/lib/mongodb/utils.js (100%) create mode 100644 node_modules/mongoose/node_modules/mongodb/package.json rename node_modules/{ => mongoose/node_modules}/mongodb/repo_node_418.js (100%) rename node_modules/{ => mongoose/node_modules}/mongodb/wercker.yml (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/.npmignore (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/LICENSE (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/lib/charset.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/lib/encoding.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/lib/language.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/lib/mediaType.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/lib/negotiator.js (100%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/package.json (72%) rename node_modules/{express/node_modules/accepts/node_modules => }/negotiator/readme.md (100%) rename node_modules/{express/node_modules => }/parseurl/.npmignore (100%) rename node_modules/{express/node_modules => }/parseurl/README.md (100%) rename node_modules/{express/node_modules => }/parseurl/index.js (100%) rename node_modules/{express/node_modules => }/parseurl/package.json (61%) rename node_modules/{express/node_modules => }/path-to-regexp/.npmignore (100%) rename node_modules/{express/node_modules => }/path-to-regexp/History.md (100%) rename node_modules/{express/node_modules => }/path-to-regexp/Readme.md (100%) rename node_modules/{express/node_modules => }/path-to-regexp/component.json (100%) rename node_modules/{express/node_modules => }/path-to-regexp/index.js (100%) rename node_modules/{express/node_modules => }/path-to-regexp/package.json (78%) rename node_modules/{express/node_modules => }/path-to-regexp/test.js (100%) rename node_modules/{express/node_modules => }/proxy-addr/.npmignore (100%) rename node_modules/{express/node_modules => }/proxy-addr/History.md (100%) rename node_modules/{express/node_modules => }/proxy-addr/LICENSE (100%) rename node_modules/{express/node_modules => }/proxy-addr/README.md (100%) rename node_modules/{express/node_modules => }/proxy-addr/index.js (100%) rename node_modules/{express/node_modules => }/proxy-addr/package.json (75%) rename node_modules/{express/node_modules => }/qs/.gitmodules (100%) rename node_modules/{express/node_modules => }/qs/.npmignore (100%) rename node_modules/{express/node_modules => }/qs/Readme.md (100%) rename node_modules/{express/node_modules => }/qs/index.js (100%) rename node_modules/{express/node_modules => }/qs/package.json (59%) rename node_modules/{express/node_modules => }/range-parser/.npmignore (100%) rename node_modules/{express/node_modules => }/range-parser/History.md (100%) rename node_modules/{express/node_modules => }/range-parser/Makefile (100%) rename node_modules/{express/node_modules => }/range-parser/Readme.md (100%) rename node_modules/{express/node_modules => }/range-parser/index.js (100%) rename node_modules/{express/node_modules => }/range-parser/package.json (59%) create mode 100644 node_modules/require_optional/.npmignore create mode 100644 node_modules/require_optional/.travis.yml create mode 100644 node_modules/require_optional/HISTORY.md create mode 100644 node_modules/require_optional/LICENSE create mode 100644 node_modules/require_optional/README.md create mode 100644 node_modules/require_optional/index.js create mode 100644 node_modules/require_optional/package.json create mode 100644 node_modules/require_optional/test/nestedTest/index.js create mode 100644 node_modules/require_optional/test/nestedTest/package.json create mode 100644 node_modules/require_optional/test/require_optional_tests.js create mode 100644 node_modules/resolve-from/index.js create mode 100644 node_modules/resolve-from/license create mode 100644 node_modules/resolve-from/package.json create mode 100644 node_modules/resolve-from/readme.md create mode 100644 node_modules/saslprep/.editorconfig create mode 100644 node_modules/saslprep/.eslintrc create mode 100644 node_modules/saslprep/.gitattributes create mode 100644 node_modules/saslprep/.travis.yml create mode 100644 node_modules/saslprep/LICENSE create mode 100644 node_modules/saslprep/code-points.mem create mode 100644 node_modules/saslprep/generate-code-points.js create mode 100644 node_modules/saslprep/index.js create mode 100644 node_modules/saslprep/lib/code-points.js create mode 100644 node_modules/saslprep/lib/memory-code-points.js create mode 100644 node_modules/saslprep/lib/util.js create mode 100644 node_modules/saslprep/package.json create mode 100644 node_modules/saslprep/readme.md create mode 100644 node_modules/saslprep/test/index.js create mode 100644 node_modules/saslprep/test/util.js create mode 100644 node_modules/semver/LICENSE create mode 100644 node_modules/semver/README.md create mode 100644 node_modules/semver/bin/semver create mode 100644 node_modules/semver/package.json create mode 100644 node_modules/semver/range.bnf create mode 100644 node_modules/semver/semver.js rename node_modules/{express/node_modules => }/send/.npmignore (100%) rename node_modules/{express/node_modules => }/send/History.md (100%) rename node_modules/{express/node_modules => }/send/Readme.md (100%) rename node_modules/{express/node_modules => }/send/index.js (100%) rename node_modules/{express/node_modules => }/send/lib/send.js (100%) rename node_modules/{express/node_modules => }/send/lib/utils.js (100%) create mode 100644 node_modules/send/node_modules/debug/.jshintrc create mode 100644 node_modules/send/node_modules/debug/.npmignore create mode 100644 node_modules/send/node_modules/debug/History.md create mode 100644 node_modules/send/node_modules/debug/Makefile create mode 100644 node_modules/send/node_modules/debug/Readme.md create mode 100644 node_modules/send/node_modules/debug/browser.js create mode 100644 node_modules/send/node_modules/debug/component.json create mode 100644 node_modules/send/node_modules/debug/debug.js create mode 100644 node_modules/send/node_modules/debug/node.js create mode 100644 node_modules/send/node_modules/debug/package.json rename node_modules/{express/node_modules/serve-static/node_modules => }/send/node_modules/ms/.npmignore (100%) rename node_modules/{express/node_modules/serve-static/node_modules => }/send/node_modules/ms/README.md (100%) rename node_modules/{express/node_modules/serve-static/node_modules => }/send/node_modules/ms/index.js (100%) rename node_modules/{express/node_modules/debug => send}/node_modules/ms/package.json (55%) rename node_modules/{express/node_modules => }/send/package.json (75%) rename node_modules/{express/node_modules => }/serve-static/.npmignore (100%) rename node_modules/{express/node_modules => }/serve-static/History.md (100%) rename node_modules/{express/node_modules => }/serve-static/LICENSE (100%) rename node_modules/{express/node_modules => }/serve-static/Readme.md (100%) rename node_modules/{express/node_modules => }/serve-static/index.js (100%) create mode 100644 node_modules/serve-static/node_modules/debug/.jshintrc create mode 100644 node_modules/serve-static/node_modules/debug/.npmignore rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/debug/History.md (100%) create mode 100644 node_modules/serve-static/node_modules/debug/Makefile create mode 100644 node_modules/serve-static/node_modules/debug/Readme.md rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/debug/browser.js (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/debug/component.json (100%) rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/debug/debug.js (100%) create mode 100644 node_modules/serve-static/node_modules/debug/node.js rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/debug/package.json (69%) create mode 100644 node_modules/serve-static/node_modules/ms/.npmignore create mode 100644 node_modules/serve-static/node_modules/ms/README.md create mode 100644 node_modules/serve-static/node_modules/ms/index.js rename node_modules/{express/node_modules/serve-static/node_modules/send => serve-static}/node_modules/ms/package.json (54%) rename node_modules/{express/node_modules => }/serve-static/node_modules/parseurl/.npmignore (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/parseurl/HISTORY.md (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/parseurl/README.md (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/parseurl/index.js (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/parseurl/package.json (66%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/.npmignore (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/History.md (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/Readme.md (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/index.js (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/lib/send.js (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/lib/utils.js (100%) rename node_modules/{express/node_modules => }/serve-static/node_modules/send/package.json (74%) rename node_modules/{express/node_modules => }/serve-static/package.json (69%) rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first => sparse-bitfield}/.npmignore (54%) create mode 100644 node_modules/sparse-bitfield/.travis.yml rename node_modules/{express/node_modules/type-is/node_modules/mime-types => sparse-bitfield}/LICENSE (95%) create mode 100644 node_modules/sparse-bitfield/README.md create mode 100644 node_modules/sparse-bitfield/index.js create mode 100644 node_modules/sparse-bitfield/package.json create mode 100644 node_modules/sparse-bitfield/test.js rename node_modules/{express/node_modules/serve-static/node_modules/send/node_modules/finished => type-is}/.npmignore (100%) rename node_modules/{express/node_modules => }/type-is/HISTORY.md (100%) rename node_modules/{express/node_modules => }/type-is/README.md (100%) rename node_modules/{express/node_modules => }/type-is/index.js (100%) rename node_modules/{express/node_modules => }/type-is/package.json (75%) rename node_modules/{express/node_modules => }/utils-merge/.travis.yml (100%) rename node_modules/{express/node_modules => }/utils-merge/LICENSE (100%) rename node_modules/{express/node_modules => }/utils-merge/README.md (100%) rename node_modules/{express/node_modules => }/utils-merge/index.js (100%) rename node_modules/{express/node_modules => }/utils-merge/package.json (61%) rename node_modules/{express/node_modules/type-is => vary}/.npmignore (100%) rename node_modules/{express/node_modules => }/vary/History.md (100%) rename node_modules/{express/node_modules => }/vary/LICENSE (100%) rename node_modules/{express/node_modules => }/vary/README.md (100%) rename node_modules/{express/node_modules => }/vary/index.js (100%) rename node_modules/{express/node_modules => }/vary/package.json (74%) diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 100644 index 0000000..d592e69 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../semver/bin/semver" "$@" + ret=$? +else + node "$basedir/../semver/bin/semver" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/semver.cmd b/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..37c00a4 --- /dev/null +++ b/node_modules/.bin/semver.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\semver\bin\semver" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\semver\bin\semver" %* +) \ No newline at end of file diff --git a/node_modules/express/node_modules/accepts/.npmignore b/node_modules/accepts/.npmignore similarity index 100% rename from node_modules/express/node_modules/accepts/.npmignore rename to node_modules/accepts/.npmignore diff --git a/node_modules/express/node_modules/accepts/History.md b/node_modules/accepts/History.md similarity index 100% rename from node_modules/express/node_modules/accepts/History.md rename to node_modules/accepts/History.md diff --git a/node_modules/express/node_modules/accepts/README.md b/node_modules/accepts/README.md similarity index 100% rename from node_modules/express/node_modules/accepts/README.md rename to node_modules/accepts/README.md diff --git a/node_modules/express/node_modules/accepts/index.js b/node_modules/accepts/index.js similarity index 100% rename from node_modules/express/node_modules/accepts/index.js rename to node_modules/accepts/index.js diff --git a/node_modules/express/node_modules/accepts/package.json b/node_modules/accepts/package.json similarity index 74% rename from node_modules/express/node_modules/accepts/package.json rename to node_modules/accepts/package.json index 24d28d7..9b19a6f 100644 --- a/node_modules/express/node_modules/accepts/package.json +++ b/node_modules/accepts/package.json @@ -1,49 +1,62 @@ { - "name": "accepts", - "description": "Higher-level content negotiation", - "version": "1.0.7", + "_from": "accepts@~1.0.7", + "_id": "accepts@1.0.7", + "_inBundle": false, + "_integrity": "sha1-W1AftPBwQwmWTM2wSBclQSCNqxo=", + "_location": "/accepts", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "accepts@~1.0.7", + "name": "accepts", + "escapedName": "accepts", + "rawSpec": "~1.0.7", + "saveSpec": null, + "fetchSpec": "~1.0.7" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz", + "_shasum": "5b501fb4f0704309964ccdb048172541208dab1a", + "_spec": "accepts@~1.0.7", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/accepts" + "bugs": { + "url": "https://github.com/expressjs/accepts/issues" }, + "bundleDependencies": false, "dependencies": { "mime-types": "~1.0.0", "negotiator": "0.4.7" }, + "deprecated": false, + "description": "Higher-level content negotiation", "devDependencies": { "istanbul": "0.2.11", "mocha": "*", "should": "*" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --require should --reporter dot test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require should --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require should --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/accepts/issues" - }, - "homepage": "https://github.com/expressjs/accepts", - "_id": "accepts@1.0.7", + "directories": {}, "dist": { "shasum": "5b501fb4f0704309964ccdb048172541208dab1a", "tarball": "http://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz" }, - "_from": "accepts@>=1.0.7 <1.1.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/accepts", + "license": "MIT", "maintainers": [ { "name": "jongleberry", @@ -74,7 +87,15 @@ "email": "fishrock123@rocketmail.com" } ], - "directories": {}, - "_shasum": "5b501fb4f0704309964ccdb048172541208dab1a", - "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz" + "name": "accepts", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/accepts.git" + }, + "scripts": { + "test": "mocha --require should --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require should --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require should --reporter spec test/" + }, + "version": "1.0.7" } diff --git a/node_modules/bson/HISTORY.md b/node_modules/bson/HISTORY.md new file mode 100644 index 0000000..63953a2 --- /dev/null +++ b/node_modules/bson/HISTORY.md @@ -0,0 +1,253 @@ + +# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) + + +### Bug Fixes + +* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) + + + + +## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) + + +### Bug Fixes + +* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) + + + + +## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) + + +### Bug Fixes + +* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) +* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) +* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) +* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) + + + + +## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) + + +### Features + +* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) + + + + +## 1.0.5 (2018-02-26) + + +### Bug Fixes + +* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) +* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) + + + +1.0.4 2016-01-11 +---------------- +- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. + +1.0.3 2016-01-03 +---------------- +- Fixed toString for ObjectId so it will work with inspect. + +1.0.2 2016-01-02 +---------------- +- Minor optimizations for ObjectID to use Buffer.from where available. + +1.0.1 2016-12-06 +---------------- +- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. + +1.0.0 2016-12-06 +---------------- +- Introduced new BSON API and documentation. + +0.5.7 2016-11-18 +----------------- +- NODE-848 BSON Regex flags must be alphabetically ordered. + +0.5.6 2016-10-19 +----------------- +- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. +- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). + +0.5.5 2016-09-15 +----------------- +- Added DBPointer up conversion to DBRef + +0.5.4 2016-08-23 +----------------- +- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. + +0.5.3 2016-07-11 +----------------- +- Throw error if ObjectId is not a string or a buffer. + +0.5.2 2016-07-11 +----------------- +- All values encoded big-endian style for ObjectId. + +0.5.1 2016-07-11 +----------------- +- Fixed encoding/decoding issue in ObjectId timestamp generation. +- Removed BinaryParser dependency from the serializer/deserializer. + +0.5.0 2016-07-05 +----------------- +- Added Decimal128 type and extended test suite to include entire bson corpus. + +0.4.23 2016-04-08 +----------------- +- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. +- Remove one package from dependency due to having been pulled from NPM. + +0.4.22 2016-03-04 +----------------- +- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). +- Fixed issue with undefined type on deserializing. + +0.4.21 2016-01-12 +----------------- +- Minor optimizations to avoid non needed object creation. + +0.4.20 2015-10-15 +----------------- +- Added bower file to repository. +- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) + +0.4.19 2015-10-15 +----------------- +- Remove all support for bson-ext. + +0.4.18 2015-10-15 +----------------- +- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 +- add option for deserializing binary into Buffer object #116 + +0.4.17 2015-10-15 +----------------- +- Validate regexp string for null bytes and throw if there is one. + +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/node_modules/bson/LICENSE b/node_modules/bson/LICENSE.md similarity index 100% rename from node_modules/bson/LICENSE rename to node_modules/bson/LICENSE.md diff --git a/node_modules/bson/README.md b/node_modules/bson/README.md index 5cac5b9..0688341 100644 --- a/node_modules/bson/README.md +++ b/node_modules/bson/README.md @@ -1,69 +1,170 @@ -Javascript + C++ BSON parser -============================ +# BSON parser -This BSON parser is primarily meant to be used with the `mongodb` node.js driver. -However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. -The current build is located in the `browser_build/bson.js` file. +BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). + +This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` A simple example of how to use BSON in the browser: ```html - - - - - + + - - ``` -A simple example of how to use BSON in `node.js`: +A simple example of how to use BSON in `Node.js`: -```javascript -var bson = require("bson"); -var BSON = bson.BSONPure.BSON; -var Long = bson.BSONPure.Long; +```js +// Get BSON parser class +var BSON = require('bson') +// Get the Long type +var Long = BSON.Long; +// Create a bson parser instance +var bson = new BSON(); -var doc = {long: Long.fromNumber(100)} +// Serialize document +var doc = { long: Long.fromNumber(100) } // Serialize a document -var data = BSON.serialize(doc, false, true, false); -console.log("data:", data); +var data = bson.serialize(doc) +console.log('data:', data) // Deserialize the resulting Buffer -var doc_2 = BSON.deserialize(data); -console.log("doc_2:", doc_2); +var doc_2 = bson.deserialize(data) +console.log('doc_2:', doc_2) ``` -The API consists of two simple methods to serialize/deserialize objects to/from BSON format: - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. +## Installation + +`npm install bson` + +## API + +### BSON types + +For all BSON types documentation, please refer to the following sources: + * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) + * [BSON Spec](https://bsonspec.org/) + +### BSON serialization and deserialiation + +**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. + +#### BSON.serialize + +The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. + + * `BSON.serialize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.serializeWithBufferAndIndex + +The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + + * `BSON.serializeWithBufferAndIndex(object, buffer, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. + * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + +#### BSON.calculateObjectSize + +The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. + + * `BSON.calculateObjectSize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.deserialize + +The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. + + * `BSON.deserialize(buffer, options)` + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + +#### BSON.deserializeStream + +The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. + + * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +var bson = new BSON(); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(bson.deserialize(bson.serialize(obj))); +``` diff --git a/node_modules/bson/bower.json b/node_modules/bson/bower.json new file mode 100644 index 0000000..b32140e --- /dev/null +++ b/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/node_modules/bson/browser_build/bson.js b/node_modules/bson/browser_build/bson.js index 8e942dd..a02bf14 100644 --- a/node_modules/bson/browser_build/bson.js +++ b/node_modules/bson/browser_build/bson.js @@ -1,4843 +1,17748 @@ -var bson = (function(){ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(1); + module.exports = __webpack_require__(327); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + __webpack_require__(2); + + __webpack_require__(323); + + __webpack_require__(324); + + if (global._babelPolyfill) { + throw new Error("only one instance of babel-polyfill is allowed"); + } + global._babelPolyfill = true; + + var DEFINE_PROPERTY = "defineProperty"; + function define(O, key, value) { + O[key] || Object[DEFINE_PROPERTY](O, key, { + writable: true, + configurable: true, + value: value + }); + } + + define(String.prototype, "padLeft", "".padStart); + define(String.prototype, "padRight", "".padEnd); + + "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { + [][key] && define(Array, key, Function.call.bind([][key])); + }); + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(3); + __webpack_require__(51); + __webpack_require__(52); + __webpack_require__(53); + __webpack_require__(54); + __webpack_require__(56); + __webpack_require__(59); + __webpack_require__(60); + __webpack_require__(61); + __webpack_require__(62); + __webpack_require__(63); + __webpack_require__(64); + __webpack_require__(65); + __webpack_require__(66); + __webpack_require__(67); + __webpack_require__(69); + __webpack_require__(71); + __webpack_require__(73); + __webpack_require__(75); + __webpack_require__(78); + __webpack_require__(79); + __webpack_require__(80); + __webpack_require__(84); + __webpack_require__(86); + __webpack_require__(88); + __webpack_require__(91); + __webpack_require__(92); + __webpack_require__(93); + __webpack_require__(94); + __webpack_require__(96); + __webpack_require__(97); + __webpack_require__(98); + __webpack_require__(99); + __webpack_require__(100); + __webpack_require__(101); + __webpack_require__(102); + __webpack_require__(104); + __webpack_require__(105); + __webpack_require__(106); + __webpack_require__(108); + __webpack_require__(109); + __webpack_require__(110); + __webpack_require__(112); + __webpack_require__(114); + __webpack_require__(115); + __webpack_require__(116); + __webpack_require__(117); + __webpack_require__(118); + __webpack_require__(119); + __webpack_require__(120); + __webpack_require__(121); + __webpack_require__(122); + __webpack_require__(123); + __webpack_require__(124); + __webpack_require__(125); + __webpack_require__(126); + __webpack_require__(131); + __webpack_require__(132); + __webpack_require__(136); + __webpack_require__(137); + __webpack_require__(138); + __webpack_require__(139); + __webpack_require__(141); + __webpack_require__(142); + __webpack_require__(143); + __webpack_require__(144); + __webpack_require__(145); + __webpack_require__(146); + __webpack_require__(147); + __webpack_require__(148); + __webpack_require__(149); + __webpack_require__(150); + __webpack_require__(151); + __webpack_require__(152); + __webpack_require__(153); + __webpack_require__(154); + __webpack_require__(155); + __webpack_require__(157); + __webpack_require__(158); + __webpack_require__(160); + __webpack_require__(161); + __webpack_require__(167); + __webpack_require__(168); + __webpack_require__(170); + __webpack_require__(171); + __webpack_require__(172); + __webpack_require__(176); + __webpack_require__(177); + __webpack_require__(178); + __webpack_require__(179); + __webpack_require__(180); + __webpack_require__(182); + __webpack_require__(183); + __webpack_require__(184); + __webpack_require__(185); + __webpack_require__(188); + __webpack_require__(190); + __webpack_require__(191); + __webpack_require__(192); + __webpack_require__(194); + __webpack_require__(196); + __webpack_require__(198); + __webpack_require__(199); + __webpack_require__(200); + __webpack_require__(202); + __webpack_require__(203); + __webpack_require__(204); + __webpack_require__(205); + __webpack_require__(216); + __webpack_require__(220); + __webpack_require__(221); + __webpack_require__(223); + __webpack_require__(224); + __webpack_require__(228); + __webpack_require__(229); + __webpack_require__(231); + __webpack_require__(232); + __webpack_require__(233); + __webpack_require__(234); + __webpack_require__(235); + __webpack_require__(236); + __webpack_require__(237); + __webpack_require__(238); + __webpack_require__(239); + __webpack_require__(240); + __webpack_require__(241); + __webpack_require__(242); + __webpack_require__(243); + __webpack_require__(244); + __webpack_require__(245); + __webpack_require__(246); + __webpack_require__(247); + __webpack_require__(248); + __webpack_require__(249); + __webpack_require__(251); + __webpack_require__(252); + __webpack_require__(253); + __webpack_require__(254); + __webpack_require__(255); + __webpack_require__(257); + __webpack_require__(258); + __webpack_require__(259); + __webpack_require__(261); + __webpack_require__(262); + __webpack_require__(263); + __webpack_require__(264); + __webpack_require__(265); + __webpack_require__(266); + __webpack_require__(267); + __webpack_require__(268); + __webpack_require__(270); + __webpack_require__(271); + __webpack_require__(273); + __webpack_require__(274); + __webpack_require__(275); + __webpack_require__(276); + __webpack_require__(279); + __webpack_require__(280); + __webpack_require__(282); + __webpack_require__(283); + __webpack_require__(284); + __webpack_require__(285); + __webpack_require__(287); + __webpack_require__(288); + __webpack_require__(289); + __webpack_require__(290); + __webpack_require__(291); + __webpack_require__(292); + __webpack_require__(293); + __webpack_require__(294); + __webpack_require__(295); + __webpack_require__(296); + __webpack_require__(298); + __webpack_require__(299); + __webpack_require__(300); + __webpack_require__(301); + __webpack_require__(302); + __webpack_require__(303); + __webpack_require__(304); + __webpack_require__(305); + __webpack_require__(306); + __webpack_require__(307); + __webpack_require__(308); + __webpack_require__(310); + __webpack_require__(311); + __webpack_require__(312); + __webpack_require__(313); + __webpack_require__(314); + __webpack_require__(315); + __webpack_require__(316); + __webpack_require__(317); + __webpack_require__(318); + __webpack_require__(319); + __webpack_require__(320); + __webpack_require__(321); + __webpack_require__(322); + module.exports = __webpack_require__(9); + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // ECMAScript 6 symbols shim + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var DESCRIPTORS = __webpack_require__(6); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var META = __webpack_require__(22).KEY; + var $fails = __webpack_require__(7); + var shared = __webpack_require__(23); + var setToStringTag = __webpack_require__(25); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var wksExt = __webpack_require__(27); + var wksDefine = __webpack_require__(28); + var enumKeys = __webpack_require__(29); + var isArray = __webpack_require__(44); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var createDesc = __webpack_require__(17); + var _create = __webpack_require__(45); + var gOPNExt = __webpack_require__(48); + var $GOPD = __webpack_require__(50); + var $DP = __webpack_require__(11); + var $keys = __webpack_require__(30); + var gOPD = $GOPD.f; + var dP = $DP.f; + var gOPN = gOPNExt.f; + var $Symbol = global.Symbol; + var $JSON = global.JSON; + var _stringify = $JSON && $JSON.stringify; + var PROTOTYPE = 'prototype'; + var HIDDEN = wks('_hidden'); + var TO_PRIMITIVE = wks('toPrimitive'); + var isEnum = {}.propertyIsEnumerable; + var SymbolRegistry = shared('symbol-registry'); + var AllSymbols = shared('symbols'); + var OPSymbols = shared('op-symbols'); + var ObjectProto = Object[PROTOTYPE]; + var USE_NATIVE = typeof $Symbol == 'function'; + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; + }) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); + } : dP; + + var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; + }; + + var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; + } : function (it) { + return it instanceof $Symbol; + }; + + var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); + }; + var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; + }; + var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; + }; + + // 19.4.1.1 Symbol([description]) + if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(43).f = $propertyIsEnumerable; + __webpack_require__(42).f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !__webpack_require__(24)) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + + for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' + ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + + for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + + $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } + }); + + $export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }); + + // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; + })), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } + }); + + // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, 'Symbol'); + // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, 'Math', true); + // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, 'JSON', true); + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); + if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function (it, key) { + return hasOwnProperty.call(it, key); + }; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(7)(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } + }; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var ctx = __webpack_require__(20); + var PROTOTYPE = 'prototype'; + + var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if (target) redefine(target, key, out, type & $export.U); + // export + if (exports[key] != out) hide(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } + }; + global.core = core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + module.exports = $export; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + var core = module.exports = { version: '2.5.7' }; + if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var createDesc = __webpack_require__(17); + module.exports = __webpack_require__(6) ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); + } : function (object, key, value) { + object[key] = value; + return object; + }; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var IE8_DOM_DEFINE = __webpack_require__(14); + var toPrimitive = __webpack_require__(16); + var dP = Object.defineProperty; + + exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; + }; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; + }; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { + return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var document = __webpack_require__(4).document; + // typeof document.createElement is 'object' in old IE + var is = isObject(document) && isObject(document.createElement); + module.exports = function (it) { + return is ? document.createElement(it) : {}; + }; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(13); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); + }; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var has = __webpack_require__(5); + var SRC = __webpack_require__(19)('src'); + var TO_STRING = 'toString'; + var $toString = Function[TO_STRING]; + var TPL = ('' + $toString).split(TO_STRING); + + __webpack_require__(9).inspectSource = function (it) { + return $toString.call(it); + }; + + (module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) has(val, 'name') || hide(val, 'name', key); + if (O[key] === val) return; + if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + hide(O, key, val); + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); + }); + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + + var id = 0; + var px = Math.random(); + module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + + // optional / simple context binding + var aFunction = __webpack_require__(21); + module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; + }; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; + }; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + + var META = __webpack_require__(19)('meta'); + var isObject = __webpack_require__(13); + var has = __webpack_require__(5); + var setDesc = __webpack_require__(11).f; + var id = 0; + var isExtensible = Object.isExtensible || function () { + return true; + }; + var FREEZE = !__webpack_require__(7)(function () { + return isExtensible(Object.preventExtensions({})); + }); + var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); + }; + var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; + }; + var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; + }; + // add metadata on freeze-family methods calling + var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; + }; + var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var SHARED = '__core-js_shared__'; + var store = global[SHARED] || (global[SHARED] = {}); + + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); + })('versions', []).push({ + version: core.version, + mode: __webpack_require__(24) ? 'pure' : 'global', + copyright: '© 2018 Denis Pushkarev (zloirock.ru)' + }); + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + + module.exports = false; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + + var def = __webpack_require__(11).f; + var has = __webpack_require__(5); + var TAG = __webpack_require__(26)('toStringTag'); + + module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); + }; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + + var store = __webpack_require__(23)('wks'); + var uid = __webpack_require__(19); + var Symbol = __webpack_require__(4).Symbol; + var USE_SYMBOL = typeof Symbol == 'function'; + + var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); + }; + + $exports.store = store; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + + exports.f = __webpack_require__(26); + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var LIBRARY = __webpack_require__(24); + var wksExt = __webpack_require__(27); + var defineProperty = __webpack_require__(11).f; + module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); + }; + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; + }; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(31); + var enumBugKeys = __webpack_require__(41); + + module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); + }; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + + var has = __webpack_require__(5); + var toIObject = __webpack_require__(32); + var arrayIndexOf = __webpack_require__(36)(false); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + + module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; + }; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(33); + var defined = __webpack_require__(35); + module.exports = function (it) { + return IObject(defined(it)); + }; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(34); + // eslint-disable-next-line no-prototype-builtins + module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); + }; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = function (it) { + return toString.call(it).slice(8, -1); + }; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; + }; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + var toAbsoluteIndex = __webpack_require__(39); + module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; + }; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.15 ToLength + var toInteger = __webpack_require__(38); + var min = Math.min; + module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 + }; + + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + + // 7.1.4 ToInteger + var ceil = Math.ceil; + var floor = Math.floor; + module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var max = Math.max; + var min = Math.min; + module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + var shared = __webpack_require__(23)('keys'); + var uid = __webpack_require__(19); + module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); + }; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + + // IE 8- don't enum bug keys + module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' + ).split(','); + + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + + exports.f = Object.getOwnPropertySymbols; + + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + + exports.f = {}.propertyIsEnumerable; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(34); + module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; + }; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(12); + var dPs = __webpack_require__(46); + var enumBugKeys = __webpack_require__(41); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var Empty = function () { /* empty */ }; + var PROTOTYPE = 'prototype'; + + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(15)('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(47).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); + }; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var anObject = __webpack_require__(12); + var getKeys = __webpack_require__(30); + + module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + + var document = __webpack_require__(4).document; + module.exports = document && document.documentElement; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(32); + var gOPN = __webpack_require__(49).f; + var toString = {}.toString; + + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + + var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } + }; + + module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); + }; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(31); + var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); + + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); + }; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + + var pIE = __webpack_require__(43); + var createDesc = __webpack_require__(17); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var IE8_DOM_DEFINE = __webpack_require__(14); + var gOPD = Object.getOwnPropertyDescriptor; + + exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); + }; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, 'Object', { create: __webpack_require__(45) }); + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + var toIObject = __webpack_require__(32); + var $getOwnPropertyDescriptor = __webpack_require__(50).f; + + __webpack_require__(55)('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor(toIObject(it), key); + }; + }); + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var fails = __webpack_require__(7); + module.exports = function (KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); + }; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(57); + var $getPrototypeOf = __webpack_require__(58); + + __webpack_require__(55)('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return $getPrototypeOf(toObject(it)); + }; + }); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(35); + module.exports = function (it) { + return Object(defined(it)); + }; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(5); + var toObject = __webpack_require__(57); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var ObjectProto = Object.prototype; + + module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; + }; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(57); + var $keys = __webpack_require__(30); + + __webpack_require__(55)('keys', function () { + return function keys(it) { + return $keys(toObject(it)); + }; + }); + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 Object.getOwnPropertyNames(O) + __webpack_require__(55)('getOwnPropertyNames', function () { + return __webpack_require__(48).f; + }); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.5 Object.freeze(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('freeze', function ($freeze) { + return function freeze(it) { + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; + }); + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.17 Object.seal(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('seal', function ($seal) { + return function seal(it) { + return $seal && isObject(it) ? $seal(meta(it)) : it; + }; + }); + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.15 Object.preventExtensions(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('preventExtensions', function ($preventExtensions) { + return function preventExtensions(it) { + return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; + }; + }); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.12 Object.isFrozen(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isFrozen', function ($isFrozen) { + return function isFrozen(it) { + return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; + }; + }); + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.13 Object.isSealed(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isSealed', function ($isSealed) { + return function isSealed(it) { + return isObject(it) ? $isSealed ? $isSealed(it) : false : true; + }; + }); + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.11 Object.isExtensible(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isExtensible', function ($isExtensible) { + return function isExtensible(it) { + return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; + }; + }); + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(8); + + $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var $assign = Object.assign; + + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(7)(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; + }) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; + } : $assign; + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.10 Object.is(value1, value2) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { is: __webpack_require__(70) }); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + + // 7.2.9 SameValue(x, y) + module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check + }; + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.3.6 Object.prototype.toString() + var classof = __webpack_require__(74); + var test = {}; + test[__webpack_require__(26)('toStringTag')] = 'z'; + if (test + '' != '[object z]') { + __webpack_require__(18)(Object.prototype, 'toString', function toString() { + return '[object ' + classof(this) + ']'; + }, true); + } + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + + // getting tag from 19.1.3.6 Object.prototype.toString() + var cof = __webpack_require__(34); + var TAG = __webpack_require__(26)('toStringTag'); + // ES3 wrong here + var ARG = cof(function () { return arguments; }()) == 'Arguments'; + + // fallback for IE11 Script Access Denied error + var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } + }; + + module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; + }; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) + var $export = __webpack_require__(8); + + $export($export.P, 'Function', { bind: __webpack_require__(76) }); + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var aFunction = __webpack_require__(21); + var isObject = __webpack_require__(13); + var invoke = __webpack_require__(77); + var arraySlice = [].slice; + var factories = {}; + + var construct = function (F, len, args) { + if (!(len in factories)) { + for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); + } return factories[len](F, args); + }; + + module.exports = Function.bind || function bind(that /* , ...args */) { + var fn = aFunction(this); + var partArgs = arraySlice.call(arguments, 1); + var bound = function (/* args... */) { + var args = partArgs.concat(arraySlice.call(arguments)); + return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); + }; + if (isObject(fn.prototype)) bound.prototype = fn.prototype; + return bound; + }; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + + // fast apply, http://jsperf.lnkit.com/fast-apply/5 + module.exports = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); + }; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11).f; + var FProto = Function.prototype; + var nameRE = /^\s*function ([^ (]*)/; + var NAME = 'name'; + + // 19.2.4.2 name + NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { + configurable: true, + get: function () { + try { + return ('' + this).match(nameRE)[1]; + } catch (e) { + return ''; + } + } + }); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var isObject = __webpack_require__(13); + var getPrototypeOf = __webpack_require__(58); + var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); + var FunctionProto = Function.prototype; + // 19.2.3.6 Function.prototype[@@hasInstance](V) + if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { + if (typeof this != 'function' || !isObject(O)) return false; + if (!isObject(this.prototype)) return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while (O = getPrototypeOf(O)) if (this.prototype === O) return true; + return false; + } }); + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 18.2.5 parseInt(string, radix) + $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseInt = __webpack_require__(4).parseInt; + var $trim = __webpack_require__(82).trim; + var ws = __webpack_require__(83); + var hex = /^[-+]?0[xX]/; + + module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { + var string = $trim(String(str), 3); + return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); + } : $parseInt; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var fails = __webpack_require__(7); + var spaces = __webpack_require__(83); + var space = '[' + spaces + ']'; + var non = '\u200b\u0085'; + var ltrim = RegExp('^' + space + space + '*'); + var rtrim = RegExp(space + space + '*$'); + + var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = fails(function () { + return !!spaces[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; + if (ALIAS) exp[ALIAS] = fn; + $export($export.P + $export.F * FORCE, 'String', exp); + }; + + // 1 -> String#trimLeft + // 2 -> String#trimRight + // 3 -> String#trim + var trim = exporter.trim = function (string, TYPE) { + string = String(defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; + + module.exports = exporter; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports) { + + module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 18.2.4 parseFloat(string) + $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseFloat = __webpack_require__(4).parseFloat; + var $trim = __webpack_require__(82).trim; + + module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; + } : $parseFloat; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var cof = __webpack_require__(34); + var inheritIfRequired = __webpack_require__(87); + var toPrimitive = __webpack_require__(16); + var fails = __webpack_require__(7); + var gOPN = __webpack_require__(49).f; + var gOPD = __webpack_require__(50).f; + var dP = __webpack_require__(11).f; + var $trim = __webpack_require__(82).trim; + var NUMBER = 'Number'; + var $Number = global[NUMBER]; + var Base = $Number; + var proto = $Number.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; + var TRIM = 'trim' in String.prototype; + + // 7.1.3 ToNumber(argument) + var toNumber = function (argument) { + var it = toPrimitive(argument, false); + if (typeof it == 'string' && it.length > 2) { + it = TRIM ? it.trim() : $trim(it, 3); + var first = it.charCodeAt(0); + var third, radix, maxCode; + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i + case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i + default: return +it; + } + for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { + code = digits.charCodeAt(i); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } return parseInt(digits, radix); + } + } return +it; + }; + + if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { + $Number = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var that = this; + return that instanceof $Number + // check on 1..constructor(foo) case + && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) + ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); + }; + for (var keys = __webpack_require__(6) ? gOPN(Base) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES6 (in case, if modules with ES6 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++) { + if (has(Base, key = keys[j]) && !has($Number, key)) { + dP($Number, key, gOPD(Base, key)); + } + } + $Number.prototype = proto; + proto.constructor = $Number; + __webpack_require__(18)(global, NUMBER, $Number); + } + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var setPrototypeOf = __webpack_require__(72).set; + module.exports = function (that, target, C) { + var S = target.constructor; + var P; + if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { + setPrototypeOf(that, P); + } return that; + }; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toInteger = __webpack_require__(38); + var aNumberValue = __webpack_require__(89); + var repeat = __webpack_require__(90); + var $toFixed = 1.0.toFixed; + var floor = Math.floor; + var data = [0, 0, 0, 0, 0, 0]; + var ERROR = 'Number.toFixed: incorrect invocation!'; + var ZERO = '0'; + + var multiply = function (n, c) { + var i = -1; + var c2 = c; + while (++i < 6) { + c2 += n * data[i]; + data[i] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + var divide = function (n) { + var i = 6; + var c = 0; + while (--i >= 0) { + c += data[i]; + data[i] = floor(c / n); + c = (c % n) * 1e7; + } + }; + var numToString = function () { + var i = 6; + var s = ''; + while (--i >= 0) { + if (s !== '' || i === 0 || data[i] !== 0) { + var t = String(data[i]); + s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; + } + } return s; + }; + var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } return n; + }; + + $export($export.P + $export.F * (!!$toFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128.0.toFixed(0) !== '1000000000000000128' + ) || !__webpack_require__(7)(function () { + // V8 ~ Android 4.3- + $toFixed.call({}); + })), 'Number', { + toFixed: function toFixed(fractionDigits) { + var x = aNumberValue(this, ERROR); + var f = toInteger(fractionDigits); + var s = ''; + var m = ZERO; + var e, z, j, k; + if (f < 0 || f > 20) throw RangeError(ERROR); + // eslint-disable-next-line no-self-compare + if (x != x) return 'NaN'; + if (x <= -1e21 || x >= 1e21) return String(x); + if (x < 0) { + s = '-'; + x = -x; + } + if (x > 1e-21) { + e = log(x * pow(2, 69, 1)) - 69; + z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = f; + while (j >= 7) { + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + m = numToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + m = numToString() + repeat.call(ZERO, f); + } + } + if (f > 0) { + k = m.length; + m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); + } else { + m = s + m; + } return m; + } + }); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + + var cof = __webpack_require__(34); + module.exports = function (it, msg) { + if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); + return +it; + }; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + + module.exports = function repeat(count) { + var str = String(defined(this)); + var res = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; + return res; + }; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $fails = __webpack_require__(7); + var aNumberValue = __webpack_require__(89); + var $toPrecision = 1.0.toPrecision; + + $export($export.P + $export.F * ($fails(function () { + // IE7- + return $toPrecision.call(1, undefined) !== '1'; + }) || !$fails(function () { + // V8 ~ Android 4.3- + $toPrecision.call({}); + })), 'Number', { + toPrecision: function toPrecision(precision) { + var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); + return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); + } + }); + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.1 Number.EPSILON + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.2 Number.isFinite(number) + var $export = __webpack_require__(8); + var _isFinite = __webpack_require__(4).isFinite; + + $export($export.S, 'Number', { + isFinite: function isFinite(it) { + return typeof it == 'number' && _isFinite(it); + } + }); + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var isObject = __webpack_require__(13); + var floor = Math.floor; + module.exports = function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; + }; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.4 Number.isNaN(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } + }); + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.5 Number.isSafeInteger(number) + var $export = __webpack_require__(8); + var isInteger = __webpack_require__(95); + var abs = Math.abs; + + $export($export.S, 'Number', { + isSafeInteger: function isSafeInteger(number) { + return isInteger(number) && abs(number) <= 0x1fffffffffffff; + } + }); + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.6 Number.MAX_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.10 Number.MIN_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 20.1.2.12 Number.parseFloat(string) + $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 20.1.2.13 Number.parseInt(string, radix) + $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.3 Math.acosh(x) + var $export = __webpack_require__(8); + var log1p = __webpack_require__(103); + var sqrt = Math.sqrt; + var $acosh = Math.acosh; + + $export($export.S + $export.F * !($acosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + && Math.floor($acosh(Number.MAX_VALUE)) == 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + && $acosh(Infinity) == Infinity + ), 'Math', { + acosh: function acosh(x) { + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? Math.log(x) + Math.LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } + }); + + +/***/ }), +/* 103 */ +/***/ (function(module, exports) { + + // 20.2.2.20 Math.log1p(x) + module.exports = Math.log1p || function log1p(x) { + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); + }; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.5 Math.asinh(x) + var $export = __webpack_require__(8); + var $asinh = Math.asinh; + + function asinh(x) { + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); + } + + // Tor Browser bug: Math.asinh(0) -> -0 + $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.7 Math.atanh(x) + var $export = __webpack_require__(8); + var $atanh = Math.atanh; + + // Tor Browser bug: Math.atanh(-0) -> 0 + $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { + atanh: function atanh(x) { + return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; + } + }); + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.9 Math.cbrt(x) + var $export = __webpack_require__(8); + var sign = __webpack_require__(107); + + $export($export.S, 'Math', { + cbrt: function cbrt(x) { + return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); + } + }); + + +/***/ }), +/* 107 */ +/***/ (function(module, exports) { + + // 20.2.2.28 Math.sign(x) + module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + }; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.11 Math.clz32(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clz32: function clz32(x) { + return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; + } + }); + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.12 Math.cosh(x) + var $export = __webpack_require__(8); + var exp = Math.exp; + + $export($export.S, 'Math', { + cosh: function cosh(x) { + return (exp(x = +x) + exp(-x)) / 2; + } + }); + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.14 Math.expm1(x) + var $export = __webpack_require__(8); + var $expm1 = __webpack_require__(111); + + $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); + + +/***/ }), +/* 111 */ +/***/ (function(module, exports) { + + // 20.2.2.14 Math.expm1(x) + var $expm1 = Math.expm1; + module.exports = (!$expm1 + // Old FF bug + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) != -2e-17 + ) ? function expm1(x) { + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; + } : $expm1; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { fround: __webpack_require__(113) }); + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var sign = __webpack_require__(107); + var pow = Math.pow; + var EPSILON = pow(2, -52); + var EPSILON32 = pow(2, -23); + var MAX32 = pow(2, 127) * (2 - EPSILON32); + var MIN32 = pow(2, -126); + + var roundTiesToEven = function (n) { + return n + 1 / EPSILON - 1 / EPSILON; + }; + + module.exports = Math.fround || function fround(x) { + var $abs = Math.abs(x); + var $sign = sign(x); + var a, result; + if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + // eslint-disable-next-line no-self-compare + if (result > MAX32 || result != result) return $sign * Infinity; + return $sign * result; + }; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) + var $export = __webpack_require__(8); + var abs = Math.abs; + + $export($export.S, 'Math', { + hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * Math.sqrt(sum); + } + }); + + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.18 Math.imul(x, y) + var $export = __webpack_require__(8); + var $imul = Math.imul; + + // some WebKit versions fails with big numbers, some has wrong arity + $export($export.S + $export.F * __webpack_require__(7)(function () { + return $imul(0xffffffff, 5) != -5 || $imul.length != 2; + }), 'Math', { + imul: function imul(x, y) { + var UINT16 = 0xffff; + var xn = +x; + var yn = +y; + var xl = UINT16 & xn; + var yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } + }); + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.21 Math.log10(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log10: function log10(x) { + return Math.log(x) * Math.LOG10E; + } + }); + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.20 Math.log1p(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { log1p: __webpack_require__(103) }); + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.22 Math.log2(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log2: function log2(x) { + return Math.log(x) / Math.LN2; + } + }); + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.28 Math.sign(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { sign: __webpack_require__(107) }); + + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.30 Math.sinh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + // V8 near Chromium 38 has a problem with very small numbers + $export($export.S + $export.F * __webpack_require__(7)(function () { + return !Math.sinh(-2e-17) != -2e-17; + }), 'Math', { + sinh: function sinh(x) { + return Math.abs(x = +x) < 1 + ? (expm1(x) - expm1(-x)) / 2 + : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); + } + }); + + +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.33 Math.tanh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + $export($export.S, 'Math', { + tanh: function tanh(x) { + var a = expm1(x = +x); + var b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } + }); + + +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.34 Math.trunc(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + trunc: function trunc(it) { + return (it > 0 ? Math.floor : Math.ceil)(it); + } + }); + + +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toAbsoluteIndex = __webpack_require__(39); + var fromCharCode = String.fromCharCode; + var $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars + var res = []; + var aLen = arguments.length; + var i = 0; + var code; + while (aLen > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + + $export($export.S, 'String', { + // 21.1.2.4 String.raw(callSite, ...substitutions) + raw: function raw(callSite) { + var tpl = toIObject(callSite.raw); + var len = toLength(tpl.length); + var aLen = arguments.length; + var res = []; + var i = 0; + while (len > i) { + res.push(String(tpl[i++])); + if (i < aLen) res.push(String(arguments[i])); + } return res.join(''); + } + }); + + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.1.3.25 String.prototype.trim() + __webpack_require__(82)('trim', function ($trim) { + return function trim() { + return $trim(this, 3); + }; + }); + + +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $at = __webpack_require__(127)(true); + + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(128)(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index + // 21.1.5.2.1 %StringIteratorPrototype%.next() + }, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; + }); + + +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + // true -> String#at + // false -> String#codePointAt + module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var $iterCreate = __webpack_require__(130); + var setToStringTag = __webpack_require__(25); + var getPrototypeOf = __webpack_require__(58); + var ITERATOR = __webpack_require__(26)('iterator'); + var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` + var FF_ITERATOR = '@@iterator'; + var KEYS = 'keys'; + var VALUES = 'values'; + + var returnThis = function () { return this; }; + + module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; + }; + + +/***/ }), +/* 129 */ +/***/ (function(module, exports) { + + module.exports = {}; + + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var create = __webpack_require__(45); + var descriptor = __webpack_require__(17); + var setToStringTag = __webpack_require__(25); + var IteratorPrototype = {}; + + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); + + module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); + }; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(false); + $export($export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var ENDS_WITH = 'endsWith'; + var $endsWith = ''[ENDS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { + endsWith: function endsWith(searchString /* , endPosition = @length */) { + var that = context(this, searchString, ENDS_WITH); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); + var search = String(searchString); + return $endsWith + ? $endsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } + }); + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + + // helper for String#{startsWith, endsWith, includes} + var isRegExp = __webpack_require__(134); + var defined = __webpack_require__(35); + + module.exports = function (that, searchString, NAME) { + if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); + return String(defined(that)); + }; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.8 IsRegExp(argument) + var isObject = __webpack_require__(13); + var cof = __webpack_require__(34); + var MATCH = __webpack_require__(26)('match'); + module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); + }; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + + var MATCH = __webpack_require__(26)('match'); + module.exports = function (KEY) { + var re = /./; + try { + '/./'[KEY](re); + } catch (e) { + try { + re[MATCH] = false; + return !'/./'[KEY](re); + } catch (f) { /* empty */ } + } return true; + }; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.7 String.prototype.includes(searchString, position = 0) + 'use strict'; + var $export = __webpack_require__(8); + var context = __webpack_require__(133); + var INCLUDES = 'includes'; + + $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { + includes: function includes(searchString /* , position = 0 */) { + return !!~context(this, searchString, INCLUDES) + .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + + $export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: __webpack_require__(90) + }); + + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var STARTS_WITH = 'startsWith'; + var $startsWith = ''[STARTS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { + startsWith: function startsWith(searchString /* , position = 0 */) { + var that = context(this, searchString, STARTS_WITH); + var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return $startsWith + ? $startsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } + }); + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.2 String.prototype.anchor(name) + __webpack_require__(140)('anchor', function (createHTML) { + return function anchor(name) { + return createHTML(this, 'a', 'name', name); + }; + }); + + +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var createHTML = function (string, tag, attribute, value) { + var S = String(defined(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; + }; + module.exports = function (NAME, exec) { + var O = {}; + O[NAME] = exec(createHTML); + $export($export.P + $export.F * fails(function () { + var test = ''[NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }), 'String', O); + }; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.3 String.prototype.big() + __webpack_require__(140)('big', function (createHTML) { + return function big() { + return createHTML(this, 'big', '', ''); + }; + }); + + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.4 String.prototype.blink() + __webpack_require__(140)('blink', function (createHTML) { + return function blink() { + return createHTML(this, 'blink', '', ''); + }; + }); + + +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.5 String.prototype.bold() + __webpack_require__(140)('bold', function (createHTML) { + return function bold() { + return createHTML(this, 'b', '', ''); + }; + }); + + +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.6 String.prototype.fixed() + __webpack_require__(140)('fixed', function (createHTML) { + return function fixed() { + return createHTML(this, 'tt', '', ''); + }; + }); + + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.7 String.prototype.fontcolor(color) + __webpack_require__(140)('fontcolor', function (createHTML) { + return function fontcolor(color) { + return createHTML(this, 'font', 'color', color); + }; + }); + + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.8 String.prototype.fontsize(size) + __webpack_require__(140)('fontsize', function (createHTML) { + return function fontsize(size) { + return createHTML(this, 'font', 'size', size); + }; + }); + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.9 String.prototype.italics() + __webpack_require__(140)('italics', function (createHTML) { + return function italics() { + return createHTML(this, 'i', '', ''); + }; + }); + + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.10 String.prototype.link(url) + __webpack_require__(140)('link', function (createHTML) { + return function link(url) { + return createHTML(this, 'a', 'href', url); + }; + }); + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.11 String.prototype.small() + __webpack_require__(140)('small', function (createHTML) { + return function small() { + return createHTML(this, 'small', '', ''); + }; + }); + + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.12 String.prototype.strike() + __webpack_require__(140)('strike', function (createHTML) { + return function strike() { + return createHTML(this, 'strike', '', ''); + }; + }); + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.13 String.prototype.sub() + __webpack_require__(140)('sub', function (createHTML) { + return function sub() { + return createHTML(this, 'sub', '', ''); + }; + }); + + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.14 String.prototype.sup() + __webpack_require__(140)('sup', function (createHTML) { + return function sup() { + return createHTML(this, 'sup', '', ''); + }; + }); + + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.3.1 / 15.9.4.4 Date.now() + var $export = __webpack_require__(8); + + $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + + $export($export.P + $export.F * __webpack_require__(7)(function () { + return new Date(NaN).toJSON() !== null + || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; + }), 'Date', { + // eslint-disable-next-line no-unused-vars + toJSON: function toJSON(key) { + var O = toObject(this); + var pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } + }); + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var $export = __webpack_require__(8); + var toISOString = __webpack_require__(156); + + // PhantomJS / old WebKit has a broken implementations + $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { + toISOString: toISOString + }); + + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var fails = __webpack_require__(7); + var getTime = Date.prototype.getTime; + var $toISOString = Date.prototype.toISOString; + + var lz = function (num) { + return num > 9 ? num : '0' + num; + }; + + // PhantomJS / old WebKit has a broken implementations + module.exports = (fails(function () { + return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; + }) || !fails(function () { + $toISOString.call(new Date(NaN)); + })) ? function toISOString() { + if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); + var d = this; + var y = d.getUTCFullYear(); + var m = d.getUTCMilliseconds(); + var s = y < 0 ? '-' : y > 9999 ? '+' : ''; + return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; + } : $toISOString; + + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + + var DateProto = Date.prototype; + var INVALID_DATE = 'Invalid Date'; + var TO_STRING = 'toString'; + var $toString = DateProto[TO_STRING]; + var getTime = DateProto.getTime; + if (new Date(NaN) + '' != INVALID_DATE) { + __webpack_require__(18)(DateProto, TO_STRING, function toString() { + var value = getTime.call(this); + // eslint-disable-next-line no-self-compare + return value === value ? $toString.call(this) : INVALID_DATE; + }); + } + + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + + var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); + var proto = Date.prototype; + + if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + var NUMBER = 'number'; + + module.exports = function (hint) { + if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); + return toPrimitive(anObject(this), hint != NUMBER); + }; + + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) + var $export = __webpack_require__(8); + + $export($export.S, 'Array', { isArray: __webpack_require__(44) }); + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var ctx = __webpack_require__(20); + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var toLength = __webpack_require__(37); + var createProperty = __webpack_require__(164); + var getIterFn = __webpack_require__(165); + + $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } + }); + + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + + // call something on iterator step with safe closing on error + var anObject = __webpack_require__(12); + module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } + }; + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + + // check on default Array iterator + var Iterators = __webpack_require__(129); + var ITERATOR = __webpack_require__(26)('iterator'); + var ArrayProto = Array.prototype; + + module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); + }; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $defineProperty = __webpack_require__(11); + var createDesc = __webpack_require__(17); + + module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; + }; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + + var classof = __webpack_require__(74); + var ITERATOR = __webpack_require__(26)('iterator'); + var Iterators = __webpack_require__(129); + module.exports = __webpack_require__(9).getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; + }; + + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + + var ITERATOR = __webpack_require__(26)('iterator'); + var SAFE_CLOSING = false; + + try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); + } catch (e) { /* empty */ } + + module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; + }; + + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var createProperty = __webpack_require__(164); + + // WebKit Array.of isn't generic + $export($export.S + $export.F * __webpack_require__(7)(function () { + function F() { /* empty */ } + return !(Array.of.call(F) instanceof F); + }), 'Array', { + // 22.1.2.3 Array.of( ...items) + of: function of(/* ...args */) { + var index = 0; + var aLen = arguments.length; + var result = new (typeof this == 'function' ? this : Array)(aLen); + while (aLen > index) createProperty(result, index, arguments[index++]); + result.length = aLen; + return result; + } + }); + + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.13 Array.prototype.join(separator) + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var arrayJoin = [].join; + + // fallback for not array-like strings + $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { + join: function join(separator) { + return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); + } + }); + + +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var fails = __webpack_require__(7); + + module.exports = function (method, arg) { + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call + arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); + }); + }; + + +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var html = __webpack_require__(47); + var cof = __webpack_require__(34); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var arraySlice = [].slice; + + // fallback for not array-like ES3 strings and DOM objects + $export($export.P + $export.F * __webpack_require__(7)(function () { + if (html) arraySlice.call(html); + }), 'Array', { + slice: function slice(begin, end) { + var len = toLength(this.length); + var klass = cof(this); + end = end === undefined ? len : end; + if (klass == 'Array') return arraySlice.call(this, begin, end); + var start = toAbsoluteIndex(begin, len); + var upTo = toAbsoluteIndex(end, len); + var size = toLength(upTo - start); + var cloned = new Array(size); + var i = 0; + for (; i < size; i++) cloned[i] = klass == 'String' + ? this.charAt(start + i) + : this[start + i]; + return cloned; + } + }); + + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var fails = __webpack_require__(7); + var $sort = [].sort; + var test = [1, 2, 3]; + + $export($export.P + $export.F * (fails(function () { + // IE8- + test.sort(undefined); + }) || !fails(function () { + // V8 bug + test.sort(null); + // Old WebKit + }) || !__webpack_require__(169)($sort)), 'Array', { + // 22.1.3.25 Array.prototype.sort(comparefn) + sort: function sort(comparefn) { + return comparefn === undefined + ? $sort.call(toObject(this)) + : $sort.call(toObject(this), aFunction(comparefn)); + } + }); + + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $forEach = __webpack_require__(173)(0); + var STRICT = __webpack_require__(169)([].forEach, true); + + $export($export.P + $export.F * !STRICT, 'Array', { + // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) + forEach: function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { + + // 0 -> Array#forEach + // 1 -> Array#map + // 2 -> Array#filter + // 3 -> Array#some + // 4 -> Array#every + // 5 -> Array#find + // 6 -> Array#findIndex + var ctx = __webpack_require__(20); + var IObject = __webpack_require__(33); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var asc = __webpack_require__(174); + module.exports = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || asc; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IObject(O); + var f = ctx(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; + }; + + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + + // 9.4.2.3 ArraySpeciesCreate(originalArray, length) + var speciesConstructor = __webpack_require__(175); + + module.exports = function (original, length) { + return new (speciesConstructor(original))(length); + }; + + +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var isArray = __webpack_require__(44); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (original) { + var C; + if (isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; + }; + + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $map = __webpack_require__(173)(1); + + $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { + // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) + map: function map(callbackfn /* , thisArg */) { + return $map(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $filter = __webpack_require__(173)(2); + + $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { + // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) + filter: function filter(callbackfn /* , thisArg */) { + return $filter(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $some = __webpack_require__(173)(3); + + $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { + // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) + some: function some(callbackfn /* , thisArg */) { + return $some(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $every = __webpack_require__(173)(4); + + $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { + // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) + every: function every(callbackfn /* , thisArg */) { + return $every(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { + // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) + reduce: function reduce(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], false); + } + }); + + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var toLength = __webpack_require__(37); + + module.exports = function (that, callbackfn, aLen, memo, isRight) { + aFunction(callbackfn); + var O = toObject(that); + var self = IObject(O); + var length = toLength(O.length); + var index = isRight ? length - 1 : 0; + var i = isRight ? -1 : 1; + if (aLen < 2) for (;;) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (isRight ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { + // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) + reduceRight: function reduceRight(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], true); + } + }); + + +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $indexOf = __webpack_require__(36)(false); + var $native = [].indexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) + indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { + return NEGATIVE_ZERO + // convert -0 to +0 + ? $native.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments[1]); + } + }); + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var $native = [].lastIndexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; + var O = toIObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; + return -1; + } + }); + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); + + __webpack_require__(187)('copyWithin'); + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + + module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; + }; + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.31 Array.prototype[@@unscopables] + var UNSCOPABLES = __webpack_require__(26)('unscopables'); + var ArrayProto = Array.prototype; + if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); + module.exports = function (key) { + ArrayProto[UNSCOPABLES][key] = true; + }; + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { fill: __webpack_require__(189) }); + + __webpack_require__(187)('fill'); + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var aLen = arguments.length; + var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); + var end = aLen > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; + }; + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(5); + var KEY = 'find'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(6); + var KEY = 'findIndex'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + findIndex: function findIndex(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(193)('Array'); + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var dP = __webpack_require__(11); + var DESCRIPTORS = __webpack_require__(6); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (KEY) { + var C = global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); + }; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var addToUnscopables = __webpack_require__(187); + var step = __webpack_require__(195); + var Iterators = __webpack_require__(129); + var toIObject = __webpack_require__(32); + + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind + // 22.1.5.2.1 %ArrayIteratorPrototype%.next() + }, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); + }, 'values'); + + // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array; + + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + + +/***/ }), +/* 195 */ +/***/ (function(module, exports) { + + module.exports = function (done, value) { + return { value: value, done: !!done }; + }; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var inheritIfRequired = __webpack_require__(87); + var dP = __webpack_require__(11).f; + var gOPN = __webpack_require__(49).f; + var isRegExp = __webpack_require__(134); + var $flags = __webpack_require__(197); + var $RegExp = global.RegExp; + var Base = $RegExp; + var proto = $RegExp.prototype; + var re1 = /a/g; + var re2 = /a/g; + // "new" creates a new object, old webkit buggy here + var CORRECT_NEW = new $RegExp(re1) !== re1; + + if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { + re2[__webpack_require__(26)('match')] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; + }))) { + $RegExp = function RegExp(p, f) { + var tiRE = this instanceof $RegExp; + var piRE = isRegExp(p); + var fiU = f === undefined; + return !tiRE && piRE && p.constructor === $RegExp && fiU ? p + : inheritIfRequired(CORRECT_NEW + ? new Base(piRE && !fiU ? p.source : p, f) + : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) + , tiRE ? this : proto, $RegExp); + }; + var proxy = function (key) { + key in $RegExp || dP($RegExp, key, { + configurable: true, + get: function () { return Base[key]; }, + set: function (it) { Base[key] = it; } + }); + }; + for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); + proto.constructor = $RegExp; + $RegExp.prototype = proto; + __webpack_require__(18)(global, 'RegExp', $RegExp); + } + + __webpack_require__(193)('RegExp'); + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.2.5.3 get RegExp.prototype.flags + var anObject = __webpack_require__(12); + module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; + }; + + +/***/ }), +/* 198 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + __webpack_require__(199); + var anObject = __webpack_require__(12); + var $flags = __webpack_require__(197); + var DESCRIPTORS = __webpack_require__(6); + var TO_STRING = 'toString'; + var $toString = /./[TO_STRING]; + + var define = function (fn) { + __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); + }; + + // 21.2.5.14 RegExp.prototype.toString() + if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { + define(function toString() { + var R = anObject(this); + return '/'.concat(R.source, '/', + 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); + }); + // FF44- RegExp#toString has a wrong name + } else if ($toString.name != TO_STRING) { + define(function toString() { + return $toString.call(this); + }); + } + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.2.5.3 get RegExp.prototype.flags() + if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { + configurable: true, + get: __webpack_require__(197) + }); + + +/***/ }), +/* 200 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@match logic + __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { + // 21.1.3.11 String.prototype.match(regexp) + return [function match(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[MATCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, $match]; + }); + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var wks = __webpack_require__(26); + + module.exports = function (KEY, length, exec) { + var SYMBOL = wks(KEY); + var fns = exec(defined, SYMBOL, ''[KEY]); + var strfn = fns[0]; + var rxfn = fns[1]; + if (fails(function () { + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) != 7; + })) { + redefine(String.prototype, KEY, strfn); + hide(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { return rxfn.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function (string) { return rxfn.call(string, this); } + ); + } + }; + + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@replace logic + __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { + // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) + return [function replace(searchValue, replaceValue) { + 'use strict'; + var O = defined(this); + var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; + return fn !== undefined + ? fn.call(searchValue, O, replaceValue) + : $replace.call(String(O), searchValue, replaceValue); + }, $replace]; + }); + + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@search logic + __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { + // 21.1.3.15 String.prototype.search(regexp) + return [function search(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[SEARCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, $search]; + }); + + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@split logic + __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { + 'use strict'; + var isRegExp = __webpack_require__(134); + var _split = $split; + var $push = [].push; + var $SPLIT = 'split'; + var LENGTH = 'length'; + var LAST_INDEX = 'lastIndex'; + if ( + 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || + 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || + 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || + '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || + '.'[$SPLIT](/()()/)[LENGTH] > 1 || + ''[$SPLIT](/.?/)[LENGTH] + ) { + var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group + // based on es5-shim implementation, need to rework it + $split = function (separator, limit) { + var string = String(this); + if (separator === undefined && limit === 0) return []; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) return _split.call(string, separator, limit); + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var separator2, match, lastIndex, lastLength, i; + // Doesn't need flags gy, but they don't hurt + if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); + while (match = separatorCopy.exec(string)) { + // `separatorCopy.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0][LENGTH]; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG + // eslint-disable-next-line no-loop-func + if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { + for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; + }); + if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); + lastLength = match[0][LENGTH]; + lastLastIndex = lastIndex; + if (output[LENGTH] >= splitLimit) break; + } + if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop + } + if (lastLastIndex === string[LENGTH]) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; + }; + // Chakra, V8 + } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { + $split = function (separator, limit) { + return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); + }; + } + // 21.1.3.17 String.prototype.split(separator, limit) + return [function split(separator, limit) { + var O = defined(this); + var fn = separator == undefined ? undefined : separator[SPLIT]; + return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); + }, $split]; + }); + + +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var ctx = __webpack_require__(20); + var classof = __webpack_require__(74); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var aFunction = __webpack_require__(21); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var speciesConstructor = __webpack_require__(208); + var task = __webpack_require__(209).set; + var microtask = __webpack_require__(210)(); + var newPromiseCapabilityModule = __webpack_require__(211); + var perform = __webpack_require__(212); + var userAgent = __webpack_require__(213); + var promiseResolve = __webpack_require__(214); + var PROMISE = 'Promise'; + var TypeError = global.TypeError; + var process = global.process; + var versions = process && process.versions; + var v8 = versions && versions.v8 || ''; + var $Promise = global[PROMISE]; + var isNode = classof(process) == 'process'; + var empty = function () { /* empty */ }; + var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; + var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; + + var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') + && promise.then(empty) instanceof FakePromise + // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // we can't detect it synchronously, so just check versions + && v8.indexOf('6.6') !== 0 + && userAgent.indexOf('Chrome/66') === -1; + } catch (e) { /* empty */ } + }(); + + // helpers + var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // may throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + if (domain && !exited) domain.exit(); + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); + }; + var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); + }; + var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; + }; + var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); + }; + var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); + }; + var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } + }; + + // constructor polyfill + if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(215)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); + __webpack_require__(25)($Promise, PROMISE); + __webpack_require__(193)(PROMISE); + Wrapper = __webpack_require__(9)[PROMISE]; + + // statics + $export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } + }); + $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); + } + }); + $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { + $Promise.all(iter)['catch'](empty); + })), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } + }); + + +/***/ }), +/* 206 */ +/***/ (function(module, exports) { + + module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; + }; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var anObject = __webpack_require__(12); + var toLength = __webpack_require__(37); + var getIterFn = __webpack_require__(165); + var BREAK = {}; + var RETURN = {}; + var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); + var f = ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = call(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } + }; + exports.BREAK = BREAK; + exports.RETURN = RETURN; + + +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.3.20 SpeciesConstructor(O, defaultConstructor) + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var SPECIES = __webpack_require__(26)('species'); + module.exports = function (O, D) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); + }; + + +/***/ }), +/* 209 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var invoke = __webpack_require__(77); + var html = __webpack_require__(47); + var cel = __webpack_require__(15); + var global = __webpack_require__(4); + var process = global.process; + var setTask = global.setImmediate; + var clearTask = global.clearImmediate; + var MessageChannel = global.MessageChannel; + var Dispatch = global.Dispatch; + var counter = 0; + var queue = {}; + var ONREADYSTATECHANGE = 'onreadystatechange'; + var defer, channel, port; + var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var listener = function (event) { + run.call(event.data); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (__webpack_require__(34)(process) == 'process') { + defer = function (id) { + process.nextTick(ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { + defer = function (id) { + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in cel('script')) { + defer = function (id) { + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(ctx(run, id, 1), 0); + }; + } + } + module.exports = { + set: setTask, + clear: clearTask + }; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var macrotask = __webpack_require__(209).set; + var Observer = global.MutationObserver || global.WebKitMutationObserver; + var process = global.process; + var Promise = global.Promise; + var isNode = __webpack_require__(34)(process) == 'process'; + + module.exports = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(global.navigator && global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + var promise = Promise.resolve(undefined); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; + }; + + +/***/ }), +/* 211 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 25.4.1.5 NewPromiseCapability(C) + var aFunction = __webpack_require__(21); + + function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + } + + module.exports.f = function (C) { + return new PromiseCapability(C); + }; + + +/***/ }), +/* 212 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } + }; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var navigator = global.navigator; + + module.exports = navigator && navigator.userAgent || ''; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var newPromiseCapability = __webpack_require__(211); + + module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; + }; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + + var redefine = __webpack_require__(18); + module.exports = function (target, src, safe) { + for (var key in src) redefine(target, key, src[key], safe); + return target; + }; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var MAP = 'Map'; + + // 23.1 Map Objects + module.exports = __webpack_require__(219)(MAP, function (get) { + return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = strong.getEntry(validate(this, MAP), key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); + } + }, strong, true); + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var dP = __webpack_require__(11).f; + var create = __webpack_require__(45); + var redefineAll = __webpack_require__(215); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var $iterDefine = __webpack_require__(128); + var step = __webpack_require__(195); + var setSpecies = __webpack_require__(193); + var DESCRIPTORS = __webpack_require__(6); + var fastKey = __webpack_require__(22).fastKey; + var validate = __webpack_require__(218); + var SIZE = DESCRIPTORS ? '_s' : 'size'; + + var getEntry = function (that, key) { + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return that._i[index]; + // frozen object case + for (entry = that._f; entry; entry = entry.n) { + if (entry.k == key) return entry; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { + entry.r = true; + if (entry.p) entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = validate(this, NAME); + var entry = getEntry(that, key); + if (entry) { + var next = entry.n; + var prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if (prev) prev.n = next; + if (next) next.p = prev; + if (that._f == entry) that._f = next; + if (that._l == entry) that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + validate(this, NAME); + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.n : this._f) { + f(entry.v, entry.k, this); + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(validate(this, NAME), key); + } + }); + if (DESCRIPTORS) dP(C.prototype, 'size', { + get: function () { + return validate(this, NAME)[SIZE]; + } + }); + return C; + }, + def: function (that, key, value) { + var entry = getEntry(that, key); + var prev, index; + // change existing entry + if (entry) { + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if (!that._f) that._f = entry; + if (prev) prev.n = entry; + that[SIZE]++; + // add to index + if (index !== 'F') that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function (C, NAME, IS_MAP) { + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function (iterated, kind) { + this._t = validate(iterated, NAME); // target + this._k = kind; // kind + this._l = undefined; // previous + }, function () { + var that = this; + var kind = that._k; + var entry = that._l; + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + // get next entry + if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if (kind == 'keys') return step(0, entry.k); + if (kind == 'values') return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); + } + }; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it, TYPE) { + if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); + return it; + }; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var redefineAll = __webpack_require__(215); + var meta = __webpack_require__(22); + var forOf = __webpack_require__(207); + var anInstance = __webpack_require__(206); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var $iterDetect = __webpack_require__(166); + var setToStringTag = __webpack_require__(25); + var inheritIfRequired = __webpack_require__(87); + + module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { + var Base = global[NAME]; + var C = Base; + var ADDER = IS_MAP ? 'set' : 'add'; + var proto = C && C.prototype; + var O = {}; + var fixMethod = function (KEY) { + var fn = proto[KEY]; + redefine(proto, KEY, + KEY == 'delete' ? function (a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'has' ? function has(a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'get' ? function get(a) { + return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } + : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } + ); + }; + if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { + new C().entries().next(); + }))) { + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + meta.NEED = true; + } else { + var instance = new C(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new C(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); + if (!ACCEPT_ITERABLES) { + C = wrapper(function (target, iterable) { + anInstance(target, C, NAME); + var that = inheritIfRequired(new Base(), target, C); + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + return that; + }); + C.prototype = proto; + proto.constructor = C; + } + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method + if (IS_WEAK && proto.clear) delete proto.clear; + } + + setToStringTag(C, NAME); + + O[NAME] = C; + $export($export.G + $export.W + $export.F * (C != Base), O); + + if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); + + return C; + }; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var SET = 'Set'; + + // 23.2 Set Objects + module.exports = __webpack_require__(219)(SET, function (get) { + return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); + } + }, strong); + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var each = __webpack_require__(173)(0); + var redefine = __webpack_require__(18); + var meta = __webpack_require__(22); + var assign = __webpack_require__(68); + var weak = __webpack_require__(222); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var validate = __webpack_require__(218); + var WEAK_MAP = 'WeakMap'; + var getWeak = meta.getWeak; + var isExtensible = Object.isExtensible; + var uncaughtFrozenStore = weak.ufstore; + var tmp = {}; + var InternalMap; + + var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; + }; + + var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + if (isObject(key)) { + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return weak.def(validate(this, WEAK_MAP), key, value); + } + }; + + // 23.3 WeakMap Objects + var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); + + // IE11 WeakMap frozen keys fix + if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { + InternalMap = weak.getConstructor(wrapper, WEAK_MAP); + assign(InternalMap.prototype, methods); + meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function (key) { + var proto = $WeakMap.prototype; + var method = proto[key]; + redefine(proto, key, function (a, b) { + // store frozen objects on internal weakmap shim + if (isObject(a) && !isExtensible(a)) { + if (!this._f) this._f = new InternalMap(); + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); + } + + +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var redefineAll = __webpack_require__(215); + var getWeak = __webpack_require__(22).getWeak; + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var createArrayMethod = __webpack_require__(173); + var $has = __webpack_require__(5); + var validate = __webpack_require__(218); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var id = 0; + + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function (that) { + return that._l || (that._l = new UncaughtFrozenStore()); + }; + var UncaughtFrozenStore = function () { + this.a = []; + }; + var findUncaughtFrozen = function (store, key) { + return arrayFind(store.a, function (it) { + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function (key) { + var index = arrayFindIndex(this.a, function (it) { + return it[0] === key; + }); + if (~index) this.a.splice(index, 1); + return !!~index; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = id++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); + return data && $has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); + return data && $has(data, this._i); + } + }); + return C; + }, + def: function (that, key, value) { + var data = getWeak(anObject(key), true); + if (data === true) uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore + }; + + +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var weak = __webpack_require__(222); + var validate = __webpack_require__(218); + var WEAK_SET = 'WeakSet'; + + // 23.4 WeakSet Objects + __webpack_require__(219)(WEAK_SET, function (get) { + return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return weak.def(validate(this, WEAK_SET), value, true); + } + }, weak, false, true); + + +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var buffer = __webpack_require__(226); + var anObject = __webpack_require__(12); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var isObject = __webpack_require__(13); + var ArrayBuffer = __webpack_require__(4).ArrayBuffer; + var speciesConstructor = __webpack_require__(208); + var $ArrayBuffer = buffer.ArrayBuffer; + var $DataView = buffer.DataView; + var $isView = $typed.ABV && ArrayBuffer.isView; + var $slice = $ArrayBuffer.prototype.slice; + var VIEW = $typed.VIEW; + var ARRAY_BUFFER = 'ArrayBuffer'; + + $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); + + $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { + // 24.1.3.1 ArrayBuffer.isView(arg) + isView: function isView(it) { + return $isView && $isView(it) || isObject(it) && VIEW in it; + } + }); + + $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { + return !new $ArrayBuffer(2).slice(1, undefined).byteLength; + }), ARRAY_BUFFER, { + // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) + slice: function slice(start, end) { + if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix + var len = anObject(this).byteLength; + var first = toAbsoluteIndex(start, len); + var fin = toAbsoluteIndex(end === undefined ? len : end, len); + var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); + var viewS = new $DataView(this); + var viewT = new $DataView(result); + var index = 0; + while (first < fin) { + viewT.setUint8(index++, viewS.getUint8(first++)); + } return result; + } + }); + + __webpack_require__(193)(ARRAY_BUFFER); + + +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var uid = __webpack_require__(19); + var TYPED = uid('typed_array'); + var VIEW = uid('view'); + var ABV = !!(global.ArrayBuffer && global.DataView); + var CONSTR = ABV; + var i = 0; + var l = 9; + var Typed; + + var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' + ).split(','); + + while (i < l) { + if (Typed = global[TypedArrayConstructors[i++]]) { + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; + } + + module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW + }; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var DESCRIPTORS = __webpack_require__(6); + var LIBRARY = __webpack_require__(24); + var $typed = __webpack_require__(225); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var fails = __webpack_require__(7); + var anInstance = __webpack_require__(206); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var gOPN = __webpack_require__(49).f; + var dP = __webpack_require__(11).f; + var arrayFill = __webpack_require__(189); + var setToStringTag = __webpack_require__(25); + var ARRAY_BUFFER = 'ArrayBuffer'; + var DATA_VIEW = 'DataView'; + var PROTOTYPE = 'prototype'; + var WRONG_LENGTH = 'Wrong length!'; + var WRONG_INDEX = 'Wrong index!'; + var $ArrayBuffer = global[ARRAY_BUFFER]; + var $DataView = global[DATA_VIEW]; + var Math = global.Math; + var RangeError = global.RangeError; + // eslint-disable-next-line no-shadow-restricted-names + var Infinity = global.Infinity; + var BaseBuffer = $ArrayBuffer; + var abs = Math.abs; + var pow = Math.pow; + var floor = Math.floor; + var log = Math.log; + var LN2 = Math.LN2; + var BUFFER = 'buffer'; + var BYTE_LENGTH = 'byteLength'; + var BYTE_OFFSET = 'byteOffset'; + var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; + var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; + var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + + // IEEE754 conversions based on https://github.com/feross/ieee754 + function packIEEE754(value, mLen, nBytes) { + var buffer = new Array(nBytes); + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; + var i = 0; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + var e, m, c; + value = abs(value); + // eslint-disable-next-line no-self-compare + if (value != value || value === Infinity) { + // eslint-disable-next-line no-self-compare + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if (value * (c = pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * 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) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; + } + function unpackIEEE754(buffer, mLen, nBytes) { + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = eLen - 7; + var i = nBytes - 1; + var s = buffer[i--]; + var e = s & 127; + var m; + s >>= 7; + for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); + } + + function unpackI32(bytes) { + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; + } + function packI8(it) { + return [it & 0xff]; + } + function packI16(it) { + return [it & 0xff, it >> 8 & 0xff]; + } + function packI32(it) { + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; + } + function packF64(it) { + return packIEEE754(it, 52, 8); + } + function packF32(it) { + return packIEEE754(it, 23, 4); + } + + function addGetter(C, key, internal) { + dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); + } + + function get(view, bytes, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); + } + function set(view, bytes, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = conversion(+value); + for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; + } + + if (!$typed.ABV) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + this._b = arrayFill.call(new Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH]; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); + } else { + if (!fails(function () { + $ArrayBuffer(1); + }) || !fails(function () { + new $ArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new $ArrayBuffer(); // eslint-disable-line no-new + new $ArrayBuffer(1.5); // eslint-disable-line no-new + new $ArrayBuffer(NaN); // eslint-disable-line no-new + return $ArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new BaseBuffer(toIndex(length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); + } + if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + hide($DataView[PROTOTYPE], $typed.VIEW, true); + exports[ARRAY_BUFFER] = $ArrayBuffer; + exports[DATA_VIEW] = $DataView; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/ecma262/#sec-toindex + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length!'); + return length; + }; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { + DataView: __webpack_require__(226).DataView + }); + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int8', 1, function (init) { + return function Int8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + if (__webpack_require__(6)) { + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var fails = __webpack_require__(7); + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var $buffer = __webpack_require__(226); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var propertyDesc = __webpack_require__(17); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var toAbsoluteIndex = __webpack_require__(39); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var classof = __webpack_require__(74); + var isObject = __webpack_require__(13); + var toObject = __webpack_require__(57); + var isArrayIter = __webpack_require__(163); + var create = __webpack_require__(45); + var getPrototypeOf = __webpack_require__(58); + var gOPN = __webpack_require__(49).f; + var getIterFn = __webpack_require__(165); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var createArrayMethod = __webpack_require__(173); + var createArrayIncludes = __webpack_require__(36); + var speciesConstructor = __webpack_require__(208); + var ArrayIterators = __webpack_require__(194); + var Iterators = __webpack_require__(129); + var $iterDetect = __webpack_require__(166); + var setSpecies = __webpack_require__(193); + var arrayFill = __webpack_require__(189); + var arrayCopyWithin = __webpack_require__(186); + var $DP = __webpack_require__(11); + var $GOPD = __webpack_require__(50); + var dP = $DP.f; + var gOPD = $GOPD.f; + var RangeError = global.RangeError; + var TypeError = global.TypeError; + var Uint8Array = global.Uint8Array; + var ARRAY_BUFFER = 'ArrayBuffer'; + var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var PROTOTYPE = 'prototype'; + var ArrayProto = Array[PROTOTYPE]; + var $ArrayBuffer = $buffer.ArrayBuffer; + var $DataView = $buffer.DataView; + var arrayForEach = createArrayMethod(0); + var arrayFilter = createArrayMethod(2); + var arraySome = createArrayMethod(3); + var arrayEvery = createArrayMethod(4); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var arrayIncludes = createArrayIncludes(true); + var arrayIndexOf = createArrayIncludes(false); + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var arrayLastIndexOf = ArrayProto.lastIndexOf; + var arrayReduce = ArrayProto.reduce; + var arrayReduceRight = ArrayProto.reduceRight; + var arrayJoin = ArrayProto.join; + var arraySort = ArrayProto.sort; + var arraySlice = ArrayProto.slice; + var arrayToString = ArrayProto.toString; + var arrayToLocaleString = ArrayProto.toLocaleString; + var ITERATOR = wks('iterator'); + var TAG = wks('toStringTag'); + var TYPED_CONSTRUCTOR = uid('typed_constructor'); + var DEF_CONSTRUCTOR = uid('def_constructor'); + var ALL_CONSTRUCTORS = $typed.CONSTR; + var TYPED_ARRAY = $typed.TYPED; + var VIEW = $typed.VIEW; + var WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function (O, length) { + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function () { + // eslint-disable-next-line no-undef + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { + new Uint8Array(1).set({}); + }); + + var toOffset = function (it, BYTES) { + var offset = toInteger(it); + if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function (it) { + if (isObject(it) && TYPED_ARRAY in it) return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function (C, length) { + if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function (O, list) { + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = allocate(C, length); + while (length > index) result[index] = list[index++]; + return result; + }; + + var addGetter = function (it, key, internal) { + dP(it, key, { get: function () { return this._d[internal]; } }); + }; + + var $from = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iterFn = getIterFn(O); + var i, length, values, result, step, iterator; + if (iterFn != undefined && !isArrayIter(iterFn)) { + for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { + values.push(step.value); + } O = values; + } + if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); + for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = allocate(this, length); + while (length > index) result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString() { + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /* , end */) { + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /* , thisArg */) { + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /* , thisArg */) { + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /* , thisArg */) { + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /* , thisArg */) { + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /* , thisArg */) { + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /* , fromIndex */) { + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /* , fromIndex */) { + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator) { // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /* , thisArg */) { + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse() { + var that = this; + var length = validate(that).length; + var middle = Math.floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /* , thisArg */) { + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn) { + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end) { + var O = validate(this); + var length = O.length; + var $begin = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end) { + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /* , offset */) { + validate(this); + var offset = toOffset(arguments[1], 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError(WRONG_LENGTH); + while (index < len) this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries() { + return arrayEntries.call(validate(this)); + }, + keys: function keys() { + return arrayKeys.call(validate(this)); + }, + values: function values() { + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function (target, key) { + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key) { + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc) { + if (isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ) { + target[key] = desc.value; + return target; + } return dP(target, key, desc); + }; + + if (!ALL_CONSTRUCTORS) { + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if (fails(function () { arrayToString.call({}); })) { + arrayToString = arrayToLocaleString = function toString() { + return arrayJoin.call(this); + }; + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function () { /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function () { return this[TYPED_ARRAY]; } + }); + + // eslint-disable-next-line max-statements + module.exports = function (KEY, BYTES, wrapper, CLAMPED) { + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + KEY; + var SETTER = 'set' + KEY; + var TypedArray = global[NAME]; + var Base = TypedArray || {}; + var TAC = TypedArray && getPrototypeOf(TypedArray); + var FORCED = !TypedArray || !$typed.ABV; + var O = {}; + var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function (that, index) { + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function (that, index, value) { + var data = that._d; + if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function (that, index) { + dP(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (FORCED) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME, '_d'); + var index = 0; + var offset = 0; + var buffer, byteLength, length, klass; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (TYPED_ARRAY in data) { + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if (!fails(function () { + TypedArray(1); + }) || !fails(function () { + new TypedArray(-1); // eslint-disable-line no-new + }) || !$iterDetect(function (iter) { + new TypedArray(); // eslint-disable-line no-new + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(1.5); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if (!isObject(data)) return new Base(toIndex(data)); + if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if (TYPED_ARRAY in data) return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { + if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR]; + var CORRECT_ITER_NAME = !!$nativeIterator + && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); + var $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { + dP(TypedArrayPrototype, TAG, { + get: function () { return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES + }); + + $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { + from: $from, + of: $of + }); + + if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; + + $export($export.P + $export.F * fails(function () { + new TypedArray(1).slice(); + }), NAME, { slice: $slice }); + + $export($export.P + $export.F * (fails(function () { + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); + }) || !fails(function () { + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, { toLocaleString: $toLocaleString }); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); + }; + } else module.exports = function () { /* empty */ }; + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }, true); + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int16', 2, function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint16', 2, function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int32', 4, function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint32', 4, function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 237 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float32', 4, function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float64', 8, function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var rApply = (__webpack_require__(4).Reflect || {}).apply; + var fApply = Function.apply; + // MS Edge argumentsList argument is optional + $export($export.S + $export.F * !__webpack_require__(7)(function () { + rApply(function () { /* empty */ }); + }), 'Reflect', { + apply: function apply(target, thisArgument, argumentsList) { + var T = aFunction(target); + var L = anObject(argumentsList); + return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); + } + }); + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) + var $export = __webpack_require__(8); + var create = __webpack_require__(45); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var bind = __webpack_require__(76); + var rConstruct = (__webpack_require__(4).Reflect || {}).construct; + + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ } + return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); + }); + var ARGS_BUG = !fails(function () { + rConstruct(function () { /* empty */ }); + }); + + $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { + construct: function construct(Target, args /* , newTarget */) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: return new Target(); + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args))(); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) + var dP = __webpack_require__(11); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + + // MS Edge has broken Reflect.defineProperty - throwing instead of returning false + $export($export.S + $export.F * __webpack_require__(7)(function () { + // eslint-disable-next-line no-undef + Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); + }), 'Reflect', { + defineProperty: function defineProperty(target, propertyKey, attributes) { + anObject(target); + propertyKey = toPrimitive(propertyKey, true); + anObject(attributes); + try { + dP.f(target, propertyKey, attributes); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.4 Reflect.deleteProperty(target, propertyKey) + var $export = __webpack_require__(8); + var gOPD = __webpack_require__(50).f; + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + deleteProperty: function deleteProperty(target, propertyKey) { + var desc = gOPD(anObject(target), propertyKey); + return desc && !desc.configurable ? false : delete target[propertyKey]; + } + }); + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 26.1.5 Reflect.enumerate(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var Enumerate = function (iterated) { + this._t = anObject(iterated); // target + this._i = 0; // next index + var keys = this._k = []; // keys + var key; + for (key in iterated) keys.push(key); + }; + __webpack_require__(130)(Enumerate, 'Object', function () { + var that = this; + var keys = that._k; + var key; + do { + if (that._i >= keys.length) return { value: undefined, done: true }; + } while (!((key = keys[that._i++]) in that._t)); + return { value: key, done: false }; + }); + + $export($export.S, 'Reflect', { + enumerate: function enumerate(target) { + return new Enumerate(target); + } + }); + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.6 Reflect.get(target, propertyKey [, receiver]) + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + + function get(target, propertyKey /* , receiver */) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var desc, proto; + if (anObject(target) === receiver) return target[propertyKey]; + if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') + ? desc.value + : desc.get !== undefined + ? desc.get.call(receiver) + : undefined; + if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); + } + + $export($export.S, 'Reflect', { get: get }); + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) + var gOPD = __webpack_require__(50); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { + return gOPD.f(anObject(target), propertyKey); + } + }); + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.8 Reflect.getPrototypeOf(target) + var $export = __webpack_require__(8); + var getProto = __webpack_require__(58); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getPrototypeOf: function getPrototypeOf(target) { + return getProto(anObject(target)); + } + }); + + +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.9 Reflect.has(target, propertyKey) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { + has: function has(target, propertyKey) { + return propertyKey in target; + } + }); + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.10 Reflect.isExtensible(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $isExtensible = Object.isExtensible; + + $export($export.S, 'Reflect', { + isExtensible: function isExtensible(target) { + anObject(target); + return $isExtensible ? $isExtensible(target) : true; + } + }); + + +/***/ }), +/* 249 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.11 Reflect.ownKeys(target) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + + // all object keys, includes non-enumerable and symbols + var gOPN = __webpack_require__(49); + var gOPS = __webpack_require__(42); + var anObject = __webpack_require__(12); + var Reflect = __webpack_require__(4).Reflect; + module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { + var keys = gOPN.f(anObject(it)); + var getSymbols = gOPS.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; + }; + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.12 Reflect.preventExtensions(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $preventExtensions = Object.preventExtensions; + + $export($export.S, 'Reflect', { + preventExtensions: function preventExtensions(target) { + anObject(target); + try { + if ($preventExtensions) $preventExtensions(target); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) + var dP = __webpack_require__(11); + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var createDesc = __webpack_require__(17); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + + function set(target, propertyKey, V /* , receiver */) { + var receiver = arguments.length < 4 ? target : arguments[3]; + var ownDesc = gOPD.f(anObject(target), propertyKey); + var existingDescriptor, proto; + if (!ownDesc) { + if (isObject(proto = getPrototypeOf(target))) { + return set(proto, propertyKey, V, receiver); + } + ownDesc = createDesc(0); + } + if (has(ownDesc, 'value')) { + if (ownDesc.writable === false || !isObject(receiver)) return false; + if (existingDescriptor = gOPD.f(receiver, propertyKey)) { + if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; + existingDescriptor.value = V; + dP.f(receiver, propertyKey, existingDescriptor); + } else dP.f(receiver, propertyKey, createDesc(0, V)); + return true; + } + return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); + } + + $export($export.S, 'Reflect', { set: set }); + + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.14 Reflect.setPrototypeOf(target, proto) + var $export = __webpack_require__(8); + var setProto = __webpack_require__(72); + + if (setProto) $export($export.S, 'Reflect', { + setPrototypeOf: function setPrototypeOf(target, proto) { + setProto.check(target, proto); + try { + setProto.set(target, proto); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/Array.prototype.includes + var $export = __webpack_require__(8); + var $includes = __webpack_require__(36)(true); + + $export($export.P, 'Array', { + includes: function includes(el /* , fromIndex = 0 */) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + __webpack_require__(187)('includes'); + + +/***/ }), +/* 255 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var aFunction = __webpack_require__(21); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatMap: function flatMap(callbackfn /* , thisArg */) { + var O = toObject(this); + var sourceLen, A; + aFunction(callbackfn); + sourceLen = toLength(O.length); + A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); + return A; + } + }); + + __webpack_require__(187)('flatMap'); + + +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray + var isArray = __webpack_require__(44); + var isObject = __webpack_require__(13); + var toLength = __webpack_require__(37); + var ctx = __webpack_require__(20); + var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); + + function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; + var element, spreadable; + + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + spreadable = false; + if (isObject(element)) { + spreadable = element[IS_CONCAT_SPREADABLE]; + spreadable = spreadable !== undefined ? !!spreadable : isArray(element); + } + + if (spreadable && depth > 0) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 0x1fffffffffffff) throw TypeError(); + target[targetIndex] = element; + } + + targetIndex++; + } + sourceIndex++; + } + return targetIndex; + } + + module.exports = flattenIntoArray; + + +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var toInteger = __webpack_require__(38); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatten: function flatten(/* depthArg = 1 */) { + var depthArg = arguments[0]; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } + }); + + __webpack_require__(187)('flatten'); + + +/***/ }), +/* 258 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/mathiasbynens/String.prototype.at + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(true); + + $export($export.P, 'String', { + at: function at(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padStart: function padStart(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); + } + }); + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = __webpack_require__(37); + var repeat = __webpack_require__(90); + var defined = __webpack_require__(35); + + module.exports = function (that, maxLength, fillString, left) { + var S = String(defined(that)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + if (intMaxLength <= stringLength || fillStr == '') return S; + var fillLen = intMaxLength - stringLength; + var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return left ? stringFiller + S : S + stringFiller; + }; + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padEnd: function padEnd(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); + } + }); + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimLeft', function ($trim) { + return function trimLeft() { + return $trim(this, 1); + }; + }, 'trimStart'); + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimRight', function ($trim) { + return function trimRight() { + return $trim(this, 2); + }; + }, 'trimEnd'); + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/String.prototype.matchAll/ + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var toLength = __webpack_require__(37); + var isRegExp = __webpack_require__(134); + var getFlags = __webpack_require__(197); + var RegExpProto = RegExp.prototype; + + var $RegExpStringIterator = function (regexp, string) { + this._r = regexp; + this._s = string; + }; + + __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { + var match = this._r.exec(this._s); + return { value: match, done: match === null }; + }); + + $export($export.P, 'String', { + matchAll: function matchAll(regexp) { + defined(this); + if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); + var S = String(this); + var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); + var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); + rx.lastIndex = toLength(regexp.lastIndex); + return new $RegExpStringIterator(rx, S); + } + }); + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('asyncIterator'); + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('observable'); + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-getownpropertydescriptors + var $export = __webpack_require__(8); + var ownKeys = __webpack_require__(250); + var toIObject = __webpack_require__(32); + var gOPD = __webpack_require__(50); + var createProperty = __webpack_require__(164); + + $export($export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = toIObject(object); + var getDesc = gOPD.f; + var keys = ownKeys(O); + var result = {}; + var i = 0; + var key, desc; + while (keys.length > i) { + desc = getDesc(O, key = keys[i++]); + if (desc !== undefined) createProperty(result, key, desc); + } + return result; + } + }); + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $values = __webpack_require__(269)(false); + + $export($export.S, 'Object', { + values: function values(it) { + return $values(it); + } + }); + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30); + var toIObject = __webpack_require__(32); + var isEnum = __webpack_require__(43).f; + module.exports = function (isEntries) { + return function (it) { + var O = toIObject(it); + var keys = getKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; + }; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $entries = __webpack_require__(269)(true); + + $export($export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } + }); + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.2 Object.prototype.__defineGetter__(P, getter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineGetter__: function __defineGetter__(P, getter) { + $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // Forced replacement prototype accessors methods + module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { + var K = Math.random(); + // In FF throws only define methods + // eslint-disable-next-line no-undef, no-useless-call + __defineSetter__.call(null, K, function () { /* empty */ }); + delete __webpack_require__(4)[K]; + }); + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.3 Object.prototype.__defineSetter__(P, setter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineSetter__: function __defineSetter__(P, setter) { + $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.4 Object.prototype.__lookupGetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupGetter__: function __lookupGetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.get; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.5 Object.prototype.__lookupSetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupSetter__: function __lookupSetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.set; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var classof = __webpack_require__(74); + var from = __webpack_require__(278); + module.exports = function (NAME) { + return function toJSON() { + if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); + return from(this); + }; + }; + + +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { + + var forOf = __webpack_require__(207); + + module.exports = function (iter, ITERATOR) { + var result = []; + forOf(iter, false, result.push, result, ITERATOR); + return result; + }; + + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); + + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of + __webpack_require__(281)('Map'); + + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { of: function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); + } }); + }; + + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of + __webpack_require__(281)('Set'); + + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of + __webpack_require__(281)('WeakMap'); + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of + __webpack_require__(281)('WeakSet'); + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from + __webpack_require__(286)('Map'); + + +/***/ }), +/* 286 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var ctx = __webpack_require__(20); + var forOf = __webpack_require__(207); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { + var mapFn = arguments[1]; + var mapping, A, n, cb; + aFunction(this); + mapping = mapFn !== undefined; + if (mapping) aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + cb = ctx(mapFn, arguments[2], 2); + forOf(source, false, function (nextItem) { + A.push(cb(nextItem, n++)); + }); + } else { + forOf(source, false, A.push, A); + } + return new this(A); + } }); + }; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from + __webpack_require__(286)('Set'); + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from + __webpack_require__(286)('WeakMap'); + + +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from + __webpack_require__(286)('WeakSet'); + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.G, { global: __webpack_require__(4) }); + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.S, 'System', { global: __webpack_require__(4) }); + + +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-is-error + var $export = __webpack_require__(8); + var cof = __webpack_require__(34); + + $export($export.S, 'Error', { + isError: function isError(it) { + return cof(it) === 'Error'; + } + }); + + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clamp: function clamp(x, lower, upper) { + return Math.min(upper, Math.max(lower, x)); + } + }); + + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); + + +/***/ }), +/* 295 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var RAD_PER_DEG = 180 / Math.PI; + + $export($export.S, 'Math', { + degrees: function degrees(radians) { + return radians * RAD_PER_DEG; + } + }); + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var scale = __webpack_require__(297); + var fround = __webpack_require__(113); + + $export($export.S, 'Math', { + fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { + return fround(scale(x, inLow, inHigh, outLow, outHigh)); + } + }); + + +/***/ }), +/* 297 */ +/***/ (function(module, exports) { + + // https://rwaldron.github.io/proposal-math-extensions/ + module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { + if ( + arguments.length === 0 + // eslint-disable-next-line no-self-compare + || x != x + // eslint-disable-next-line no-self-compare + || inLow != inLow + // eslint-disable-next-line no-self-compare + || inHigh != inHigh + // eslint-disable-next-line no-self-compare + || outLow != outLow + // eslint-disable-next-line no-self-compare + || outHigh != outHigh + ) return NaN; + if (x === Infinity || x === -Infinity) return x; + return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; + }; + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + iaddh: function iaddh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } + }); + + +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + isubh: function isubh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } + }); + + +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + imulh: function imulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >> 16; + var v1 = $v >> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } + }); + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); + + +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var DEG_PER_RAD = Math.PI / 180; + + $export($export.S, 'Math', { + radians: function radians(degrees) { + return degrees * DEG_PER_RAD; + } + }); + + +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { scale: __webpack_require__(297) }); + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + umulh: function umulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >>> 16; + var v1 = $v >>> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } + }); + + +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { + + // http://jfbastien.github.io/papers/Math.signbit.html + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { signbit: function signbit(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; + } }); + + +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-promise-finally + 'use strict'; + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var speciesConstructor = __webpack_require__(208); + var promiseResolve = __webpack_require__(214); + + $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { + var C = speciesConstructor(this, core.Promise || global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); + } }); + + +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-promise-try + var $export = __webpack_require__(8); + var newPromiseCapability = __webpack_require__(211); + var perform = __webpack_require__(212); + + $export($export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = newPromiseCapability.f(this); + var result = perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; + } }); + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); + } }); + + +/***/ }), +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { + + var Map = __webpack_require__(216); + var $export = __webpack_require__(8); + var shared = __webpack_require__(23)('metadata'); + var store = shared.store || (shared.store = new (__webpack_require__(221))()); + + var getOrCreateMetadataMap = function (target, targetKey, create) { + var targetMetadata = store.get(target); + if (!targetMetadata) { + if (!create) return undefined; + store.set(target, targetMetadata = new Map()); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) return undefined; + targetMetadata.set(targetKey, keyMetadata = new Map()); + } return keyMetadata; + }; + var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); + }; + var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); + }; + var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); + }; + var ordinaryOwnMetadataKeys = function (target, targetKey) { + var metadataMap = getOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); + return keys; + }; + var toMetaKey = function (it) { + return it === undefined || typeof it == 'symbol' ? it : String(it); + }; + var exp = function (O) { + $export($export.S, 'Reflect', O); + }; + + module.exports = { + store: store, + map: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + key: toMetaKey, + exp: exp + }; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var getOrCreateMetadataMap = metadata.map; + var store = metadata.store; + + metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); + var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; + if (metadataMap.size) return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + } }); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + var ordinaryGetMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; + }; + + metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + + var Set = __webpack_require__(220); + var from = __webpack_require__(278); + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + var ordinaryMetadataKeys = function (O, P) { + var oKeys = ordinaryOwnMetadataKeys(O, P); + var parent = getPrototypeOf(O); + if (parent === null) return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; + }; + + metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { + return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 314 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { + return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 315 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + var ordinaryHasMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; + }; + + metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 317 */ +/***/ (function(module, exports, __webpack_require__) { + + var $metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var toMetaKey = $metadata.key; + var ordinaryDefineOwnMetadata = $metadata.set; + + $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { + return function decorator(target, targetKey) { + ordinaryDefineOwnMetadata( + metadataKey, metadataValue, + (targetKey !== undefined ? anObject : aFunction)(target), + toMetaKey(targetKey) + ); + }; + } }); + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask + var $export = __webpack_require__(8); + var microtask = __webpack_require__(210)(); + var process = __webpack_require__(4).process; + var isNode = __webpack_require__(34)(process) == 'process'; + + $export($export.G, { + asap: function asap(fn) { + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } + }); + + +/***/ }), +/* 319 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/zenparsing/es-observable + var $export = __webpack_require__(8); + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var microtask = __webpack_require__(210)(); + var OBSERVABLE = __webpack_require__(26)('observable'); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var anInstance = __webpack_require__(206); + var redefineAll = __webpack_require__(215); + var hide = __webpack_require__(10); + var forOf = __webpack_require__(207); + var RETURN = forOf.RETURN; + + var getMethod = function (fn) { + return fn == null ? undefined : aFunction(fn); + }; + + var cleanupSubscription = function (subscription) { + var cleanup = subscription._c; + if (cleanup) { + subscription._c = undefined; + cleanup(); + } + }; + + var subscriptionClosed = function (subscription) { + return subscription._o === undefined; + }; + + var closeSubscription = function (subscription) { + if (!subscriptionClosed(subscription)) { + subscription._o = undefined; + cleanupSubscription(subscription); + } + }; + + var Subscription = function (observer, subscriber) { + anObject(observer); + this._c = undefined; + this._o = observer; + observer = new SubscriptionObserver(this); + try { + var cleanup = subscriber(observer); + var subscription = cleanup; + if (cleanup != null) { + if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; + else aFunction(cleanup); + this._c = cleanup; + } + } catch (e) { + observer.error(e); + return; + } if (subscriptionClosed(this)) cleanupSubscription(this); + }; + + Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe() { closeSubscription(this); } + }); + + var SubscriptionObserver = function (subscription) { + this._s = subscription; + }; + + SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + try { + var m = getMethod(observer.next); + if (m) return m.call(observer, value); + } catch (e) { + try { + closeSubscription(subscription); + } finally { + throw e; + } + } + } + }, + error: function error(value) { + var subscription = this._s; + if (subscriptionClosed(subscription)) throw value; + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.error); + if (!m) throw value; + value = m.call(observer, value); + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + }, + complete: function complete(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.complete); + value = m ? m.call(observer, value) : undefined; + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + } + } + }); + + var $Observable = function Observable(subscriber) { + anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); + }; + + redefineAll($Observable.prototype, { + subscribe: function subscribe(observer) { + return new Subscription(observer, this._f); + }, + forEach: function forEach(fn) { + var that = this; + return new (core.Promise || global.Promise)(function (resolve, reject) { + aFunction(fn); + var subscription = that.subscribe({ + next: function (value) { + try { + return fn(value); + } catch (e) { + reject(e); + subscription.unsubscribe(); + } + }, + error: reject, + complete: resolve + }); + }); + } + }); + + redefineAll($Observable, { + from: function from(x) { + var C = typeof this === 'function' ? this : $Observable; + var method = getMethod(anObject(x)[OBSERVABLE]); + if (method) { + var observable = anObject(method.call(x)); + return observable.constructor === C ? observable : new C(function (observer) { + return observable.subscribe(observer); + }); + } + return new C(function (observer) { + var done = false; + microtask(function () { + if (!done) { + try { + if (forOf(x, false, function (it) { + observer.next(it); + if (done) return RETURN; + }) === RETURN) return; + } catch (e) { + if (done) throw e; + observer.error(e); + return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + }, + of: function of() { + for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; + return new (typeof this === 'function' ? this : $Observable)(function (observer) { + var done = false; + microtask(function () { + if (!done) { + for (var j = 0; j < items.length; ++j) { + observer.next(items[j]); + if (done) return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + } + }); + + hide($Observable.prototype, OBSERVABLE, function () { return this; }); + + $export($export.G, { Observable: $Observable }); + + __webpack_require__(193)('Observable'); + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + + // ie9- setTimeout & setInterval additional parameters fix + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var userAgent = __webpack_require__(213); + var slice = [].slice; + var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check + var wrap = function (set) { + return function (fn, time /* , ...args */) { + var boundArgs = arguments.length > 2; + var args = boundArgs ? slice.call(arguments, 2) : false; + return set(boundArgs ? function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); + } : fn, time); + }; + }; + $export($export.G + $export.B + $export.F * MSIE, { + setTimeout: wrap(global.setTimeout), + setInterval: wrap(global.setInterval) + }); + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $task = __webpack_require__(209); + $export($export.G + $export.B, { + setImmediate: $task.set, + clearImmediate: $task.clear + }); + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + + var $iterators = __webpack_require__(194); + var getKeys = __webpack_require__(30); + var redefine = __webpack_require__(18); + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var wks = __webpack_require__(26); + var ITERATOR = wks('iterator'); + var TO_STRING_TAG = wks('toStringTag'); + var ArrayValues = Iterators.Array; + + var DOMIterables = { + CSSRuleList: true, // TODO: Not spec compliant, should be false. + CSSStyleDeclaration: false, + CSSValueList: false, + ClientRectList: false, + DOMRectList: false, + DOMStringList: false, + DOMTokenList: true, + DataTransferItemList: false, + FileList: false, + HTMLAllCollection: false, + HTMLCollection: false, + HTMLFormElement: false, + HTMLSelectElement: false, + MediaList: true, // TODO: Not spec compliant, should be false. + MimeTypeArray: false, + NamedNodeMap: false, + NodeList: true, + PaintRequestList: false, + Plugin: false, + PluginArray: false, + SVGLengthList: false, + SVGNumberList: false, + SVGPathSegList: false, + SVGPointList: false, + SVGStringList: false, + SVGTransformList: false, + SourceBufferList: false, + StyleSheetList: true, // TODO: Not spec compliant, should be false. + TextTrackCueList: false, + TextTrackList: false, + TouchList: false + }; + + for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { + var NAME = collections[i]; + var explicit = DOMIterables[NAME]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + var key; + if (proto) { + if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); + if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); + } + } + + +/***/ }), +/* 323 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + + !(function(global) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + runtime.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof global.process === "object" && global.process.domain) { + invoke = global.process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + runtime.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + })( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this + ); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(325); + module.exports = __webpack_require__(9).RegExp.escape; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/benjamingr/RexExp.escape + var $export = __webpack_require__(8); + var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + + $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); + + +/***/ }), +/* 326 */ +/***/ (function(module, exports) { + + module.exports = function (regExp, replace) { + var replacer = replace === Object(replace) ? function (part) { + return replace[part]; + } : replace; + return function (it) { + return String(it).replace(regExp, replacer); + }; + }; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + + var BSON = __webpack_require__(328), + Binary = __webpack_require__(350), + Code = __webpack_require__(345), + DBRef = __webpack_require__(349), + Decimal128 = __webpack_require__(346), + Double = __webpack_require__(335), + Int32 = __webpack_require__(344), + Long = __webpack_require__(334), + Map = __webpack_require__(333), + MaxKey = __webpack_require__(348), + MinKey = __webpack_require__(347), + ObjectId = __webpack_require__(337), + BSONRegExp = __webpack_require__(342), + Symbol = __webpack_require__(343), + Timestamp = __webpack_require__(336); + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Add BSON types to function creation + BSON.Binary = Binary; + BSON.Code = Code; + BSON.DBRef = DBRef; + BSON.Decimal128 = Decimal128; + BSON.Double = Double; + BSON.Int32 = Int32; + BSON.Long = Long; + BSON.Map = Map; + BSON.MaxKey = MaxKey; + BSON.MinKey = MinKey; + BSON.ObjectId = ObjectId; + BSON.ObjectID = ObjectId; + BSON.BSONRegExp = BSONRegExp; + BSON.Symbol = Symbol; + BSON.Timestamp = Timestamp; + + // Return the BSON + module.exports = BSON; + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Map = __webpack_require__(333), + Long = __webpack_require__(334), + Double = __webpack_require__(335), + Timestamp = __webpack_require__(336), + ObjectID = __webpack_require__(337), + BSONRegExp = __webpack_require__(342), + Symbol = __webpack_require__(343), + Int32 = __webpack_require__(344), + Code = __webpack_require__(345), + Decimal128 = __webpack_require__(346), + MinKey = __webpack_require__(347), + MaxKey = __webpack_require__(348), + DBRef = __webpack_require__(349), + Binary = __webpack_require__(350); + + // Parts of the parser + var deserialize = __webpack_require__(351), + serializer = __webpack_require__(352), + calculateObjectSize = __webpack_require__(355); + + /** + * @ignore + * @api private + */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + + // Current Internal Temporary Serialization Buffer + var buffer = new Buffer(MAXSIZE); + + var BSON = function () {}; + + /** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ + BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = new Buffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + }; + + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ + BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + + // Return the index + return serializationIndex - 1; + }; + + /** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ + BSON.prototype.deserialize = function (buffer, options) { + return deserialize(buffer, options); + }; + + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ + BSON.prototype.calculateObjectSize = function (object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); + }; + + /** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ + BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; + }; + + /** + * @ignore + * @api private + */ + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // Return BSON + module.exports = BSON; + module.exports.Code = Code; + module.exports.Map = Map; + module.exports.Symbol = Symbol; + module.exports.BSON = BSON; + module.exports.DBRef = DBRef; + module.exports.Binary = Binary; + module.exports.ObjectID = ObjectID; + module.exports.Long = Long; + module.exports.Timestamp = Timestamp; + module.exports.Double = Double; + module.exports.Int32 = Int32; + module.exports.MinKey = MinKey; + module.exports.MaxKey = MaxKey; + module.exports.BSONRegExp = BSONRegExp; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 329 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(330) + var ieee754 = __webpack_require__(331) + var isArray = __webpack_require__(332) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } - function exports(){ return main(); }; + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } - ties = {}; + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - aliases = {}; + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - return exports; + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) - if (cur === "." && prev !== undefined) continue; + return val + } - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) - return ret.join("/"); -}; + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; + if (val >= mul) val -= Math.pow(2, 8 * byteLength) -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; + return val + } - var i = pkg.modules.length, - id; + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } - while(i-->0){ - id = pkg.modules[i].id; + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } - return module; -} + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) -function newRequire(callingModule){ - function require(uri){ - var module, pkg; + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } - if(pkg) return pkg; - } + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } - module = pkg.index; - } + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } - module.parent = callingModule; - return module.call(); - }; - - - return require; -} + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * 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; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * 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; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // 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; -}, - - - -'index': function(module, exports, global, require, undefined){ - 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]; - } -}); + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 330 */ +/***/ (function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') + } + + +/***/ }), +/* 331 */ +/***/ (function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var 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) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var 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 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; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // 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; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * 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 { - 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 as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* 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 = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - 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 date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @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 = parseInt(Math.random() * 0xFFFFFF, 10); - -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; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * 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; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // 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; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} +/***/ }), +/* 332 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }), +/* 333 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + + // We have an ES6 Map available, return the native instance + + if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; + } else { + // We will return a polyfill + var Map = function (array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function (callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function () { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; + } + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 334 */ +/***/ (function(module, exports) { + + // 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 + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ + function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ + Long.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Long.prototype.toNumber = function () { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Long.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + 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)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + 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. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Long.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Long.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + 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. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ + 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. + * + * @method + * @return {boolean} whether this value is zero. + */ + Long.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Long.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Long.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ + Long.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ + Long.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ + Long.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ + Long.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ + Long.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Long with the given one. + * + * @method + * @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. + */ + 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. + * + * @method + * @return {Long} the negation of this value. + */ + 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. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ + 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. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ + Long.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ + 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. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ + 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; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + 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. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ + Long.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ + Long.prototype.not = function () { + return Long.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ + 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. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ + 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. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ + 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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ + 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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ + 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. + * + * @method + * @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. + */ + 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. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ + 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. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ + 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. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ + Long.fromBits = function (lowBits, highBits) { + return new Long(lowBits, highBits); + }; + + /** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @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. + */ + 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} + * @ignore + */ + 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} + * @ignore + */ + Long.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + 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} + * @ignore + */ + Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Long; + module.exports.Long = Long; + +/***/ }), +/* 335 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Double type. + * + * @class + * @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. + * + * @method + * @return {number} returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Double.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Double; + module.exports.Double = Double; + +/***/ }), +/* 336 */ +/***/ (function(module, exports) { + + // 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 + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * 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 + * @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} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ + Timestamp.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Timestamp.prototype.toNumber = function () { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Timestamp.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + 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)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + 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. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Timestamp.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Timestamp.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + 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. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ + 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. + * + * @method + * @return {boolean} whether this value is zero. + */ + Timestamp.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Timestamp.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Timestamp.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ + Timestamp.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ + Timestamp.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ + Timestamp.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ + Timestamp.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ + Timestamp.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ + Timestamp.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Timestamp with the given one. + * + * @method + * @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. + */ + 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. + * + * @method + * @return {Timestamp} the negation of this value. + */ + 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. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ + 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. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ + Timestamp.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ + 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. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ + 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; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + 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. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ + Timestamp.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ + Timestamp.prototype.not = function () { + return Timestamp.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ + 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. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ + 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. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ + 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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ + 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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ + 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. + * + * @method + * @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. + */ + 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. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + 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. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + 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. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + + /** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @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. + */ + 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} + * @ignore + */ + 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} + * @ignore + */ + Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + 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} + * @ignore + */ + Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Timestamp; + module.exports.Timestamp = Timestamp; + +/***/ }), +/* 337 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. + var inspect = 'inspect'; + + /** + * 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. + * @ignore + */ + var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + + // Check if buffer exists + try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = __webpack_require__(339).inspect.custom || 'inspect'; + } + } catch (err) { + hasBufferType = false; + } + + /** + * Create a new ObjectID instance + * + * @class + * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. + * @property {number} generationTime The generation time of this ObjectId instance + * @return {ObjectID} instance of ObjectID. + */ + var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(new Buffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + }; + + // Allow usage of ObjectId as well as ObjectID + // var ObjectId = ObjectID; + + // Precomputed hex table enables speedy hex string conversion + var hexTable = []; + for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); + } + + /** + * Return the ObjectID id as a 24 byte hex string representation + * + * @method + * @return {string} return the 24 byte hex string representation. + */ + ObjectID.prototype.toHexString = function () { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + 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 + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.getInc = function () { + return this.get_inc(); + }; + + /** + * Generate a 12 byte id buffer used in ObjectID's + * + * @method + * @param {number} [time] optional parameter allowing to pass in a second based timestamp. + * @return {Buffer} return the 12 byte id buffer string. + */ + ObjectID.prototype.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = MACHINE_ID >> 8 & 0xff; + buffer[4] = MACHINE_ID >> 16 & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = pid >> 8 & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = inc >> 8 & 0xff; + buffer[9] = inc >> 16 & 0xff; + // Return the buffer + return buffer; + }; + + /** + * Converts the id into a 24 byte hex string for printing + * + * @param {String} format The Buffer toString format parameter. + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); + }; + + /** + * Converts to a string representation of this Id. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype[inspect] = ObjectID.prototype.toString; + + /** + * Converts to its JSON representation. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toJSON = function () { + return this.toHexString(); + }; + + /** + * Compares the equality of this ObjectID with `otherID`. + * + * @method + * @param {object} otherID ObjectID instance to compare against. + * @return {boolean} the result of comparing two ObjectID's + */ + ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } + }; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated. + * + * @method + * @return {date} the generation date + */ + ObjectID.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + + /** + * @ignore + */ + ObjectID.index = ~~(Math.random() * 0xffffff); + + /** + * @ignore + */ + 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. + * + * @method + * @param {number} time an integer number representing a number of seconds. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromTime = function createFromTime(time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Return the new objectId + return new ObjectID(buffer); + }; + + // Lookup tables + //var encodeLookup = '0123456789abcdef'.split(''); + var decodeLookup = []; + i = 0; + while (i < 10) decodeLookup[0x30 + i] = i++; + while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + + var _Buffer = Buffer; + var convertToHex = function (bytes) { + return bytes.toString('hex'); + }; + + /** + * Creates an ObjectID from a hex string representation of an ObjectID. + * + * @method + * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || string != null && string.length !== 24) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); + }; + + /** + * Checks if a value is a valid bson ObjectId + * + * @method + * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. + */ + ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); + } + + return false; + }; + + /** + * @ignore + */ + Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + }, + set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = value >> 8 & 0xff; + this.id[1] = value >> 16 & 0xff; + this.id[0] = value >> 24 & 0xff; + } + }); + + /** + * Expose. + */ + module.exports = ObjectID; + module.exports.ObjectID = ObjectID; + module.exports.ObjectId = ObjectID; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer, __webpack_require__(338))) + +/***/ }), +/* 338 */ +/***/ (function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // 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. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(340); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(341); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) + +/***/ }), +/* 340 */ +/***/ (function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }), +/* 341 */ +/***/ (function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }), +/* 342 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } + } + + module.exports = BSONRegExp; + module.exports.BSONRegExp = BSONRegExp; + +/***/ }), +/* 343 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. + var inspect = Buffer ? __webpack_require__(339).inspect.custom || 'inspect' : 'inspect'; + + /** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @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. + * + * @method + * @return {String} returns the wrapped string. + */ + Symbol.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toString = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype[inspect] = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Symbol; + module.exports.Symbol = Symbol; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 344 */ +/***/ (function(module, exports) { + + /** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ + var Int32 = function (value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; + }; + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Int32.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Int32; + module.exports.Int32 = Int32; + +/***/ }), +/* 345 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ + var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; + }; + + /** + * @ignore + */ + Code.prototype.toJSON = function () { + return { scope: this.scope, code: this.code }; + }; + + module.exports = Code; + module.exports.Code = Code; + +/***/ }), +/* 346 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + + // Detect if the value is a digit + var isDigit = function (value) { + return !isNaN(parseInt(value, 10)); + }; + + // Divide two uint128 values + var divideu128 = function (value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; + }; + + // Multiply two Long values and return the 128 bit value + var multiply64x2 = function (left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; + }; + + var lessThan = function (left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; + }; + + // var longtoHex = function(value) { + // var buffer = new Buffer(8); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value.low_ & 0xff; + // buffer[index++] = (value.low_ >> 8) & 0xff; + // buffer[index++] = (value.low_ >> 16) & 0xff; + // buffer[index++] = (value.low_ >> 24) & 0xff; + // // Encode high bits + // buffer[index++] = value.high_ & 0xff; + // buffer[index++] = (value.high_ >> 8) & 0xff; + // buffer[index++] = (value.high_ >> 16) & 0xff; + // buffer[index++] = (value.high_ >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + // var int32toHex = function(value) { + // var buffer = new Buffer(4); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value & 0xff; + // buffer[index++] = (value >> 8) & 0xff; + // buffer[index++] = (value >> 16) & 0xff; + // buffer[index++] = (value >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + /** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ + var Decimal128 = function (bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; + }; + + /** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ + Decimal128.fromString = function (string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = dec.low.low_ >> 8 & 0xff; + buffer[index++] = dec.low.low_ >> 16 & 0xff; + buffer[index++] = dec.low.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = dec.low.high_ >> 8 & 0xff; + buffer[index++] = dec.low.high_ >> 16 & 0xff; + buffer[index++] = dec.low.high_ >> 24 & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = dec.high.low_ >> 8 & 0xff; + buffer[index++] = dec.high.low_ >> 16 & 0xff; + buffer[index++] = dec.high.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = dec.high.high_ >> 8 & 0xff; + buffer[index++] = dec.high.high_ >> 16 & 0xff; + buffer[index++] = dec.high.high_ >> 24 & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + }; + + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Value of combination field for NaN + // var COMBINATION_SNAN = 32; + // decimal128 exponent bias + EXPONENT_BIAS = 6176; + + /** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = high >> 26 & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 0x08 + (high >> 14 & 0x01); + } + } else { + significand_msb = high >> 14 & 0x07; + biased_exponent = high >> 17 & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); + }; + + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + + module.exports = Decimal128; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 347 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ + function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; + } + + module.exports = MinKey; + module.exports.MinKey = MinKey; + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ + function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; + } + + module.exports = MaxKey; + module.exports.MaxKey = MaxKey; + +/***/ }), +/* 349 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON DBRef type. + * + * @class + * @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 + }; + }; + + module.exports = DBRef; + module.exports.DBRef = DBRef; + +/***/ }), +/* 350 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + * @ignore + */ + + // Test if we're in Node via presence of "global" not absence of "window" + // to support hybrid environments like Electron + if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(329).Buffer; // TODO just use global Buffer + } + + /** + * 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 + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + 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. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ + 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 { + 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. + * + * @method + * @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. + * @return {null} + */ + 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, offset, 'binary'); + 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 (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 (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**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ + 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. + * + * @method + * @return {string} + */ + Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; + + // 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. + * + * @method + * @return {number} the length of the binary. + */ + Binary.prototype.length = function length() { + return this.position; + }; + + /** + * @ignore + */ + Binary.prototype.toJSON = function () { + return this.buffer != null ? this.buffer.toString('base64') : ''; + }; + + /** + * @ignore + */ + Binary.prototype.toString = function (format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; + }; + + /** + * Binary default subtype + * @ignore + */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** + * @ignore + */ + 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 + */ + var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; + }; + + 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. + */ + module.exports = Binary; + module.exports.Binary = Binary; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334).Long, + Double = __webpack_require__(335).Double, + Timestamp = __webpack_require__(336).Timestamp, + ObjectID = __webpack_require__(337).ObjectID, + Symbol = __webpack_require__(343).Symbol, + Code = __webpack_require__(345).Code, + MinKey = __webpack_require__(347).MinKey, + MaxKey = __webpack_require__(348).MaxKey, + Decimal128 = __webpack_require__(346), + Int32 = __webpack_require__(344), + DBRef = __webpack_require__(349).DBRef, + BSONRegExp = __webpack_require__(342).BSONRegExp, + Binary = __webpack_require__(350).Binary; + + var deserialize = function (buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + }; + + var deserializeObject = function (buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEvalWithHash = function (functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEval = function (functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ + BSON.BSON_DATA_DBPOINTER = 12; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = deserialize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var writeIEEE754 = __webpack_require__(353).writeIEEE754, + Long = __webpack_require__(334).Long, + MinKey = __webpack_require__(347).MinKey, + Map = __webpack_require__(333), + Binary = __webpack_require__(350).Binary; + + const normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; + + // try { + // var _Buffer = Uint8Array; + // } catch (e) { + // _Buffer = Buffer; + // } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + }; + + var serializeString = function (buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = size + 1 >> 24 & 0xff; + buffer[index + 2] = size + 1 >> 16 & 0xff; + buffer[index + 1] = size + 1 >> 8 & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeNumber = function (buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + }; + + var serializeNull = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + }; + + var serializeDate = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeBSONRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeMinMax = function (buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeObjectId = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; + }; + + var serializeBuffer = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + }; + + var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + return endIndex; + }; + + var serializeDecimal128 = function (buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; + }; + + var serializeLong = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeInt32 = function (buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return index; + }; + + var serializeDouble = function (buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + }; + + var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = codeSize >> 8 & 0xff; + buffer[index + 2] = codeSize >> 16 & 0xff; + buffer[index + 3] = codeSize >> 24 & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = totalSize >> 8 & 0xff; + buffer[startIndex++] = totalSize >> 16 & 0xff; + buffer[startIndex++] = totalSize >> 24 & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; + }; + + var serializeBinary = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; + }; + + var serializeSymbol = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + }; + + var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = size >> 8 & 0xff; + buffer[startIndex++] = size >> 16 & 0xff; + buffer[startIndex++] = size >> 24 & 0xff; + // Set index + return endIndex; + }; + + var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || value === undefined && ignoreUndefined === false) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = size >> 8 & 0xff; + buffer[startingIndex++] = size >> 16 & 0xff; + buffer[startingIndex++] = size >> 24 & 0xff; + return index; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + // var functionCache = (BSON.functionCache = {}); + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = serializeInto; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 353 */ +/***/ (function(module, exports) { + + // 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; + +/***/ }), +/* 354 */ +/***/ (function(module, exports) { + + 'use strict'; + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ + + function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); + } + + module.exports = { + normalizedFunctionString: normalizedFunctionString + }; + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334).Long, + Double = __webpack_require__(335).Double, + Timestamp = __webpack_require__(336).Timestamp, + ObjectID = __webpack_require__(337).ObjectID, + Symbol = __webpack_require__(343).Symbol, + BSONRegExp = __webpack_require__(342).BSONRegExp, + Code = __webpack_require__(345).Code, + Decimal128 = __webpack_require__(346), + MinKey = __webpack_require__(347).MinKey, + MaxKey = __webpack_require__(348).MaxKey, + DBRef = __webpack_require__(349).DBRef, + Binary = __webpack_require__(350).Binary; + + var normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; + }; + + /** + * @ignore + * @api private + */ + function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; + } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if (serializeFunctions) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; + } + } + } + + return 0; + } + + var BSON = {}; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = calculateObjectSize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/node_modules/bson/browser_build/package.json b/node_modules/bson/browser_build/package.json index 3ebb587..980db7f 100644 --- a/node_modules/bson/browser_build/package.json +++ b/node_modules/bson/browser_build/package.json @@ -1,6 +1,6 @@ { "name" : "bson" , "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" +, "main": "../" , "directories" : { "lib" : "../lib/bson" } , "engines" : { "node" : ">=0.6.0" } , "licenses" : [ { "type" : "Apache License, Version 2.0" diff --git a/node_modules/bson/index.js b/node_modules/bson/index.js new file mode 100644 index 0000000..6502552 --- /dev/null +++ b/node_modules/bson/index.js @@ -0,0 +1,46 @@ +var BSON = require('./lib/bson/bson'), + Binary = require('./lib/bson/binary'), + Code = require('./lib/bson/code'), + DBRef = require('./lib/bson/db_ref'), + Decimal128 = require('./lib/bson/decimal128'), + Double = require('./lib/bson/double'), + Int32 = require('./lib/bson/int_32'), + Long = require('./lib/bson/long'), + Map = require('./lib/bson/map'), + MaxKey = require('./lib/bson/max_key'), + MinKey = require('./lib/bson/min_key'), + ObjectId = require('./lib/bson/objectid'), + BSONRegExp = require('./lib/bson/regexp'), + Symbol = require('./lib/bson/symbol'), + Timestamp = require('./lib/bson/timestamp'); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; diff --git a/node_modules/bson/lib/bson/binary.js b/node_modules/bson/lib/bson/binary.js index 5d0acfa..f3f695d 100644 --- a/node_modules/bson/lib/bson/binary.js +++ b/node_modules/bson/lib/bson/binary.js @@ -2,13 +2,16 @@ * Module dependencies. * @ignore */ -if(typeof window === 'undefined') { + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if (typeof global !== 'undefined') { var Buffer = require('buffer').Buffer; // TODO just use global Buffer } /** * 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. @@ -23,37 +26,50 @@ if(typeof window === 'undefined') { * @return {Binary} */ function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + buffer != null && + !(typeof buffer === 'string') && + !Buffer.isBuffer(buffer) && + !(buffer instanceof Uint8Array) && + !Array.isArray(buffer) + ) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + this._bsontype = 'Binary'; - if(buffer instanceof Number) { + if (buffer instanceof Number) { this.sub_type = buffer; this.position = 0; - } else { + } else { this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; this.position = 0; } - if(buffer != null && !(buffer instanceof Number)) { + if (buffer != null && !(buffer instanceof Number)) { // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { + if (typeof buffer === 'string') { // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { + if (typeof Buffer !== 'undefined') { this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + } 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"); + throw new Error('only String, Buffer, Uint8Array or Array accepted'); } } else { - this.buffer = buffer; + this.buffer = buffer; } this.position = buffer.length; } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ + 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); @@ -61,7 +77,7 @@ function Binary(buffer, subType) { // Set position to start of buffer this.position = 0; } -}; +} /** * Updates this binary with byte_value. @@ -71,23 +87,25 @@ function Binary(buffer, subType) { */ 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"); - + 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) { + 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) { + + if (this.buffer.length > this.position) { this.buffer[this.position++] = decoded_byte; } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + 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 @@ -95,19 +113,19 @@ Binary.prototype.put = function put(byte_value) { this.buffer = buffer; this.buffer[this.position++] = decoded_byte; } else { - var buffer = null; + buffer = null; // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + 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++) { + for (var i = 0; i < this.buffer.length; i++) { buffer[i] = this.buffer[i]; } - + // Reassign the buffer this.buffer = buffer; // Write the byte @@ -125,45 +143,51 @@ Binary.prototype.put = function put(byte_value) { * @return {null} */ Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; + 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) { + if (this.buffer.length < offset + string.length) { var buffer = null; // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + 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]') { + 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)) + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); // Copy the content - for(var i = 0; i < this.position; i++) { + 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)) { + 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; + 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; + } else if ( + typeof Buffer !== 'undefined' && + typeof string === 'string' && + Buffer.isBuffer(this.buffer) + ) { + this.buffer.write(string, offset, 'binary'); + 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++) { + } else if ( + Object.prototype.toString.call(string) === '[object Uint8Array]' || + (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') + ) { + for (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++) { + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { this.buffer[offset++] = string.charCodeAt(i); } @@ -180,17 +204,18 @@ Binary.prototype.write = function write(string, offset) { * @return {Buffer} */ Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - + length = length && length > 0 ? length : this.position; + // Let's return the data based on the type we have - if(this.buffer['slice']) { + 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++) { + 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++]; } } @@ -205,25 +230,35 @@ Binary.prototype.read = function read(position, length) { * @return {string} */ Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; + asRaw = asRaw == null ? false : asRaw; // Optimize to serialize for the situation where the data == size of buffer - if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + if ( + asRaw && + typeof Buffer !== 'undefined' && + Buffer.isBuffer(this.buffer) && + this.buffer.length === this.position + ) return this.buffer; - + // 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); + 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) { + if (asRaw) { // we support the slice command use it - if(this.buffer['slice'] != null) { + 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); + 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++) { + for (var i = 0; i < this.position; i++) { newBuffer[i] = this.buffer[i]; } // Return the buffer @@ -250,18 +285,18 @@ Binary.prototype.length = function length() { */ Binary.prototype.toJSON = function() { return this.buffer != null ? this.buffer.toString('base64') : ''; -} +}; /** * @ignore */ Binary.prototype.toString = function(format) { return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} +}; /** * Binary default subtype - * @ignore + * @ignore */ var BSON_BINARY_SUBTYPE_DEFAULT = 0; @@ -270,14 +305,17 @@ var BSON_BINARY_SUBTYPE_DEFAULT = 0; */ var writeStringToArray = function(data) { // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + 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++) { + 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 @@ -285,54 +323,54 @@ var writeStringToArray = function(data) { * @ignore */ var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); } - return result; + return result; }; 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; @@ -341,4 +379,4 @@ Binary.SUBTYPE_USER_DEFINED = 128; * Expose. */ module.exports = Binary; -module.exports.Binary = Binary; \ No newline at end of file +module.exports.Binary = Binary; diff --git a/node_modules/bson/lib/bson/bson.js b/node_modules/bson/lib/bson/bson.js index fc57600..956f152 100644 --- a/node_modules/bson/lib/bson/bson.js +++ b/node_modules/bson/lib/bson/bson.js @@ -1,48 +1,224 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 +'use strict'; + +var Map = require('./map'), + Long = require('./long'), + Double = require('./double'), + Timestamp = require('./timestamp'), + ObjectID = require('./objectid'), + BSONRegExp = require('./regexp'), + Symbol = require('./symbol'), + Int32 = require('./int_32'), + Code = require('./code'), + Decimal128 = require('./decimal128'), + MinKey = require('./min_key'), + MaxKey = require('./max_key'), + DBRef = require('./db_ref'), + Binary = require('./binary'); + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} +/** + * @ignore + * @api private + */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +var buffer = new Buffer(MAXSIZE); + +var BSON = function() {}; + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = new Buffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +}; /** - * Create a new BSON instance + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. * - * @class - * @return {BSON} instance of BSON Parser. + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public */ -function BSON () {}; +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer( + finalBuffer, + object, + checkKeys, + startIndex || 0, + 0, + serializeFunctions, + ignoreUndefined + ); + + // Return the index + return serializationIndex - 1; +}; + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +}; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +}; + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function( + data, + startIndex, + numberOfDocuments, + documents, + docStartIndex, + options +) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = + data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +}; /** * @ignore * @api private */ // BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MAX = 0x7fffffff; BSON.BSON_INT32_MIN = -0x80000000; BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; BSON.BSON_INT64_MIN = -Math.pow(2, 63); // JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. /** * Number BSON Type @@ -74,12 +250,6 @@ BSON.BSON_DATA_ARRAY = 4; * @classconstant BSON_DATA_BINARY **/ BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; /** * ObjectID BSON Type * @@ -196,1378 +366,20 @@ BSON.BSON_BINARY_SUBTYPE_MD5 = 4; **/ BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - var startIndex = index; - - switch(typeof value) { - case 'string': - // console.log("+++++++++++ index string:: " + index) - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // console.log("====== key :: " + name + " size ::" + size) - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // console.log("+++++++++++ index OBJECTID:: " + index) - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) - // console.log(buffer.toString('hex')) - // console.log(buffer.toString('ascii')) - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_UNDEFINED: - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/code.js b/node_modules/bson/lib/bson/code.js index 83a42c9..c2984cd 100644 --- a/node_modules/bson/lib/bson/code.js +++ b/node_modules/bson/lib/bson/code.js @@ -7,18 +7,18 @@ * @return {Code} */ var Code = function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); + if (!(this instanceof Code)) return new Code(code, scope); this._bsontype = 'Code'; this.code = code; - this.scope = scope == null ? {} : scope; + this.scope = scope; }; /** * @ignore */ Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} + return { scope: this.scope, code: this.code }; +}; module.exports = Code; -module.exports.Code = Code; \ No newline at end of file +module.exports.Code = Code; diff --git a/node_modules/bson/lib/bson/db_ref.js b/node_modules/bson/lib/bson/db_ref.js index 06789a6..f95795b 100644 --- a/node_modules/bson/lib/bson/db_ref.js +++ b/node_modules/bson/lib/bson/db_ref.js @@ -8,13 +8,13 @@ * @return {DBRef} */ function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new 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 @@ -22,11 +22,11 @@ function DBRef(namespace, oid, db) { */ DBRef.prototype.toJSON = function() { return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db }; -} +}; module.exports = DBRef; -module.exports.DBRef = DBRef; \ No newline at end of file +module.exports.DBRef = DBRef; diff --git a/node_modules/bson/lib/bson/decimal128.js b/node_modules/bson/lib/bson/decimal128.js new file mode 100644 index 0000000..1dc2f00 --- /dev/null +++ b/node_modules/bson/lib/bson/decimal128.js @@ -0,0 +1,818 @@ +'use strict'; + +var Long = require('./long'); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); + +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +}; + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +}; + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; +}; + +// var longtoHex = function(value) { +// var buffer = new Buffer(8); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value.low_ & 0xff; +// buffer[index++] = (value.low_ >> 8) & 0xff; +// buffer[index++] = (value.low_ >> 16) & 0xff; +// buffer[index++] = (value.low_ >> 24) & 0xff; +// // Encode high bits +// buffer[index++] = value.high_ & 0xff; +// buffer[index++] = (value.high_ >> 8) & 0xff; +// buffer[index++] = (value.high_ >> 16) & 0xff; +// buffer[index++] = (value.high_ >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +// var int32toHex = function(value) { +// var buffer = new Buffer(4); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value & 0xff; +// buffer[index++] = (value >> 8) & 0xff; +// buffer[index++] = (value >> 16) & 0xff; +// buffer[index++] = (value >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +/** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +}; + +/** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high + .shiftRightUnsigned(49) + .and(Long.fromNumber(1)) + .equals(Long.fromNumber) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +}; + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +// var COMBINATION_SNAN = 32; +// decimal128 exponent bias +EXPONENT_BIAS = 6176; + +/** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +}; + +Decimal128.prototype.toJSON = function() { + return { $numberDecimal: this.toString() }; +}; + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/double.js b/node_modules/bson/lib/bson/double.js index 09ed222..523c21f 100644 --- a/node_modules/bson/lib/bson/double.js +++ b/node_modules/bson/lib/bson/double.js @@ -6,8 +6,8 @@ * @return {Double} */ function Double(value) { - if(!(this instanceof Double)) return new Double(value); - + if (!(this instanceof Double)) return new Double(value); + this._bsontype = 'Double'; this.value = value; } @@ -27,7 +27,7 @@ Double.prototype.valueOf = function() { */ Double.prototype.toJSON = function() { return this.value; -} +}; module.exports = Double; -module.exports.Double = Double; \ No newline at end of file +module.exports.Double = Double; diff --git a/node_modules/bson/lib/bson/float_parser.js b/node_modules/bson/lib/bson/float_parser.js index 6fca392..0054a2f 100644 --- a/node_modules/bson/lib/bson/float_parser.js +++ b/node_modules/bson/lib/bson/float_parser.js @@ -1,20 +1,20 @@ // 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 @@ -31,32 +31,33 @@ // 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]; + 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); + 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); + 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); + return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; @@ -65,15 +66,17 @@ var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { }; 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; + 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); @@ -86,7 +89,7 @@ var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { e--; c *= 2; } - if (e+eBias >= 1) { + if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); @@ -118,4 +121,4 @@ var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { }; exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file +exports.writeIEEE754 = writeIEEE754; diff --git a/node_modules/bson/lib/bson/int_32.js b/node_modules/bson/lib/bson/int_32.js new file mode 100644 index 0000000..85dbdec --- /dev/null +++ b/node_modules/bson/lib/bson/int_32.js @@ -0,0 +1,33 @@ +/** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ +var Int32 = function(value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +}; + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Int32; +module.exports.Int32 = Int32; diff --git a/node_modules/bson/lib/bson/long.js b/node_modules/bson/lib/bson/long.js index 6f18885..78215aa 100644 --- a/node_modules/bson/lib/bson/long.js +++ b/node_modules/bson/lib/bson/long.js @@ -41,21 +41,21 @@ * @return {Long} */ function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - + if (!(this instanceof Long)) return new Long(low, high); + this._bsontype = 'Long'; /** * @type {number} * @ignore */ - this.low_ = low | 0; // force into 32 signed bits. + this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ - this.high_ = high | 0; // force into 32 signed bits. -}; + this.high_ = high | 0; // force into 32 signed bits. +} /** * Return the int value. @@ -74,8 +74,7 @@ Long.prototype.toInt = function() { * @return {number} the closest floating-point representation to this value. */ Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** @@ -86,7 +85,7 @@ Long.prototype.toNumber = function() { */ Long.prototype.toJSON = function() { return this.toString(); -} +}; /** * Return the String value. @@ -122,9 +121,10 @@ Long.prototype.toString = function(opt_radix) { // minimize the calls to the very expensive emulated div. var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - var rem = this; + rem = this; var result = ''; - while (true) { + + while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); @@ -168,8 +168,7 @@ Long.prototype.getLowBits = function() { * @return {number} the low 32-bits as an unsigned value. */ Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; }; /** @@ -186,13 +185,13 @@ Long.prototype.getNumBitsAbs = function() { return this.negate().getNumBitsAbs(); } } else { - var val = this.high_ != 0 ? this.high_ : this.low_; + var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { + if ((val & (1 << bit)) !== 0) { break; } } - return this.high_ != 0 ? bit + 33 : bit + 1; + return this.high_ !== 0 ? bit + 33 : bit + 1; } }; @@ -203,7 +202,7 @@ Long.prototype.getNumBitsAbs = function() { * @return {boolean} whether this value is zero. */ Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; + return this.high_ === 0 && this.low_ === 0; }; /** @@ -223,7 +222,7 @@ Long.prototype.isNegative = function() { * @return {boolean} whether this value is odd. */ Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; + return (this.low_ & 1) === 1; }; /** @@ -234,7 +233,7 @@ Long.prototype.isOdd = function() { * @return {boolean} whether this Long equals the other */ Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); + return this.high_ === other.high_ && this.low_ === other.low_; }; /** @@ -245,7 +244,7 @@ Long.prototype.equals = function(other) { * @return {boolean} whether this Long does not equal the other. */ Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); + return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** @@ -346,27 +345,30 @@ 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 a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; + var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; + var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; + var b00 = other.low_ & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; - c00 &= 0xFFFF; + c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c48 += a48 + b48; - c48 &= 0xFFFF; + c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; @@ -405,15 +407,16 @@ Long.prototype.multiply = function(other) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { - return this.negate().multiply(other).negate(); + 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_)) { + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { return Long.fromNumber(this.toNumber() * other.toNumber()); } @@ -421,36 +424,39 @@ Long.prototype.multiply = function(other) { // We can skip products that would overflow. var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; + var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; + var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; + var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; + var b00 = other.low_ & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; - c00 &= 0xFFFF; + c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; + c48 &= 0xffff; return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; @@ -469,9 +475,8 @@ Long.prototype.div = function(other) { } 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 + 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 { @@ -494,7 +499,9 @@ Long.prototype.div = function(other) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { - return this.negate().div(other).negate(); + return this.negate() + .div(other) + .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); @@ -506,16 +513,16 @@ Long.prototype.div = function(other) { // 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; + 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())); + 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); + 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. @@ -602,15 +609,13 @@ Long.prototype.xor = function(other) { */ Long.prototype.shiftLeft = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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))); + return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Long.fromBits(0, low << (numBits - 32)); } @@ -626,19 +631,15 @@ Long.prototype.shiftLeft = function(numBits) { */ Long.prototype.shiftRight = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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); + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); + return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; @@ -652,16 +653,14 @@ Long.prototype.shiftRight = function(numBits) { */ Long.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { return Long.fromBits(high, 0); } else { return Long.fromBits(high >>> (numBits - 32), 0); @@ -708,9 +707,7 @@ Long.fromNumber = function(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); + return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); } }; @@ -735,7 +732,7 @@ Long.fromBits = function(lowBits, highBits) { * @return {Long} the corresponding Long value. */ Long.fromString = function(str, opt_radix) { - if (str.length == 0) { + if (str.length === 0) { throw Error('number format error: empty string'); } @@ -744,7 +741,7 @@ Long.fromString = function(str, opt_radix) { throw Error('radix out of range: ' + radix); } - if (str.charAt(0) == '-') { + 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); @@ -772,7 +769,6 @@ Long.fromString = function(str, opt_radix) { // 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} @@ -837,8 +833,7 @@ Long.ONE = Long.fromInt(1); Long.NEG_ONE = Long.fromInt(-1); /** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Long} */ Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); @@ -853,4 +848,4 @@ Long.TWO_PWR_24_ = Long.fromInt(1 << 24); * Expose. */ module.exports = Long; -module.exports.Long = Long; \ No newline at end of file +module.exports.Long = Long; diff --git a/node_modules/bson/lib/bson/map.js b/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..7edb4f2 --- /dev/null +++ b/node_modules/bson/lib/bson/map.js @@ -0,0 +1,128 @@ +'use strict'; + +// We have an ES6 Map available, return the native instance +if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function(key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function(key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function() { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; +} diff --git a/node_modules/bson/lib/bson/max_key.js b/node_modules/bson/lib/bson/max_key.js index 03ee9cd..eebca7b 100644 --- a/node_modules/bson/lib/bson/max_key.js +++ b/node_modules/bson/lib/bson/max_key.js @@ -5,10 +5,10 @@ * @return {MaxKey} A MaxKey instance */ function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; } module.exports = MaxKey; -module.exports.MaxKey = MaxKey; \ No newline at end of file +module.exports.MaxKey = MaxKey; diff --git a/node_modules/bson/lib/bson/min_key.js b/node_modules/bson/lib/bson/min_key.js index 5e120fb..15f4522 100644 --- a/node_modules/bson/lib/bson/min_key.js +++ b/node_modules/bson/lib/bson/min_key.js @@ -5,10 +5,10 @@ * @return {MinKey} A MinKey instance */ function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - + if (!(this instanceof MinKey)) return new MinKey(); + this._bsontype = 'MinKey'; } module.exports = MinKey; -module.exports.MinKey = MinKey; \ No newline at end of file +module.exports.MinKey = MinKey; diff --git a/node_modules/bson/lib/bson/objectid.js b/node_modules/bson/lib/bson/objectid.js index 1d4894a..f76ecbb 100644 --- a/node_modules/bson/lib/bson/objectid.js +++ b/node_modules/bson/lib/bson/objectid.js @@ -1,8 +1,5 @@ -/** - * Module dependencies. - * @ignore - */ -var BinaryParser = require('./binary_parser').BinaryParser; +// Custom inspect property name / symbol. +var inspect = 'inspect'; /** * Machine id. @@ -12,10 +9,20 @@ var BinaryParser = require('./binary_parser').BinaryParser; * that would mean an asyc call to gethostname, so we don't bother. * @ignore */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); +var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); // Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Check if buffer exists +try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = require('util').inspect.custom || 'inspect'; + } +} catch (err) { + hasBufferType = false; +} /** * Create a new ObjectID instance @@ -26,31 +33,51 @@ var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); * @return {ObjectID} instance of ObjectID. */ var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - if((id instanceof ObjectID)) return id; + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); this._bsontype = 'ObjectID'; - var __id = null; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid var valid = ObjectID.isValid(id); // Throw an error if it's not a valid setup - if(!valid && id != null){ - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if(valid && typeof id == 'string' && id.length == 24) { + if (!valid && id != null) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(new Buffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { return ObjectID.createFromHexString(id); - } else if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { + } else if (id != null && id.length === 12) { // assume 12 byte string this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); } - if(ObjectID.cacheHexString) this.__id = this.toHexString(); + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); }; // Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; +// var ObjectId = ObjectID; // Precomputed hex table enables speedy hex string conversion var hexTable = []; @@ -65,15 +92,28 @@ for (var i = 0; i < 256; i++) { * @return {string} return the 24 byte hex string representation. */ ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; + if (ObjectID.cacheHexString && this.__id) return this.__id; var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error( + 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + + JSON.stringify(this.id) + + ']' + ); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } for (var i = 0; i < this.id.length; i++) { hexString += hexTable[this.id.charCodeAt(i)]; } - if(ObjectID.cacheHexString) this.__id = hexString; + if (ObjectID.cacheHexString) this.__id = hexString; return hexString; }; @@ -85,7 +125,7 @@ ObjectID.prototype.toHexString = function() { * @ignore */ ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; + return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); }; /** @@ -100,33 +140,59 @@ ObjectID.prototype.getInc = function() { }; /** -* Generate a 12 byte id string used in ObjectID's +* Generate a 12 byte id buffer used in ObjectID's * * @method * @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {string} return the 12 byte id binary string. +* @return {Buffer} return the 12 byte id buffer string. */ ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); } - - 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 % 0xFFFF); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; + + // Use pid + var pid = + (typeof process === 'undefined' || process.pid === 1 + ? Math.floor(Math.random() * 100000) + : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; }; /** * Converts the id into a 24 byte hex string for printing * +* @param {String} format The Buffer toString format parameter. * @return {String} return the 24 byte hex string representation. * @ignore */ -ObjectID.prototype.toString = function() { +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) return this.toHexString(); }; @@ -136,7 +202,7 @@ ObjectID.prototype.toString = function() { * @return {String} return the 24 byte hex string representation. * @ignore */ -ObjectID.prototype.inspect = ObjectID.prototype.toString; +ObjectID.prototype[inspect] = ObjectID.prototype.toString; /** * Converts to its JSON representation. @@ -155,14 +221,28 @@ ObjectID.prototype.toJSON = function() { * @param {object} otherID ObjectID instance to compare against. * @return {boolean} the result of comparing two ObjectID's */ -ObjectID.prototype.equals = function equals (otherID) { - if(otherID == null) return false; - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} +ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if ( + typeof otherId === 'string' && + ObjectID.isValid(otherId) && + otherId.length === 12 && + this.id instanceof _Buffer + ) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +}; /** * Returns the generation date (accurate up to the second) that this ID was generated. @@ -172,19 +252,20 @@ ObjectID.prototype.equals = function equals (otherID) { */ ObjectID.prototype.getTimestamp = function() { var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + timestamp.setTime(Math.floor(time) * 1000); return timestamp; -} +}; /** * @ignore */ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); +ObjectID.index = ~~(Math.random() * 0xffffff); /** * @ignore */ -ObjectID.createPk = function createPk () { +ObjectID.createPk = function createPk() { return new ObjectID(); }; @@ -195,10 +276,27 @@ ObjectID.createPk = function createPk () { * @param {number} time an integer number representing a number of seconds. * @return {ObjectID} return the created ObjectID */ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); +ObjectID.createFromTime = function createFromTime(time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +//var encodeLookup = '0123456789abcdef'.split(''); +var decodeLookup = []; +i = 0; +while (i < 10) decodeLookup[0x30 + i] = i++; +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); }; /** @@ -208,28 +306,27 @@ ObjectID.createFromTime = function createFromTime (time) { * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. * @return {ObjectID} return the created ObjectID */ -ObjectID.createFromHexString = function createFromHexString (hexString) { +ObjectID.createFromHexString = function createFromHexString(string) { // 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'); + if (typeof string === 'undefined' || (string != null && string.length !== 24)) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); } - var result = '' - , string - , number; + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); + while (i < 24) { + array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; } - return new ObjectID(result, hexString); + return new ObjectID(array); }; /** @@ -239,31 +336,47 @@ ObjectID.createFromHexString = function createFromHexString (hexString) { * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. */ ObjectID.isValid = function isValid(id) { - if(id == null) return false; + if (id == null) return false; - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) { - return false; - } else { - // Check specifically for hex correctness - if(typeof id == 'string' && id.length == 24) return checkForHexRegExp.test(id); + if (typeof id === 'number') { return true; } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); + } + + return false; }; /** * @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(); - } +Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function() { + return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + }, + set: function(value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } }); /** @@ -271,4 +384,4 @@ Object.defineProperty(ObjectID.prototype, "generationTime", { */ module.exports = ObjectID; module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; \ No newline at end of file +module.exports.ObjectId = ObjectID; diff --git a/node_modules/bson/lib/bson/parser/calculate_size.js b/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..f174519 --- /dev/null +++ b/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,255 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + BSONRegExp = require('../regexp').BSONRegExp, + Code = require('../code').Code, + Decimal128 = require('../decimal128'), + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var calculateObjectSize = function calculateObjectSize( + object, + serializeFunctions, + ignoreUndefined +) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +}; + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if ( + value == null || + value instanceof MinKey || + value instanceof MaxKey || + value['_bsontype'] === 'MinKey' || + value['_bsontype'] === 'MaxKey' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length + ); + } else if ( + value instanceof Long || + value instanceof Double || + value instanceof Timestamp || + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' || + String.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/node_modules/bson/lib/bson/parser/deserializer.js b/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..b7f45d7 --- /dev/null +++ b/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,780 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + Int32 = require('../int_32'), + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +}; + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = + options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(binarySize)) + : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error( + 'Detected unknown BSON type ' + + elementType.toString(16) + + ' for fieldname "' + + name + + '", are you using the latest BSON parser' + ); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize; diff --git a/node_modules/bson/lib/bson/parser/serializer.js b/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..bd3e12a --- /dev/null +++ b/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,1183 @@ +'use strict'; + +var writeIEEE754 = require('../float_parser').writeIEEE754, + Long = require('../long').Long, + MinKey = require('../min_key').MinKey, + Map = require('../map'), + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// try { +// var _Buffer = Uint8Array; +// } catch (e) { +// _Buffer = Buffer; +// } + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +}; + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +}; + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +}; + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = + index + + buffer.write( + value.options + .split('') + .sort() + .join(''), + index, + 'utf8' + ); + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; +}; + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +}; + +var serializeObject = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray, + path +) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + // Write size + return endIndex; +}; + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +}; + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +}; + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +}; + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeCode = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +}; + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +}; + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +}; + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, + false, + index, + depth + 1, + serializeFunctions + ); + } else { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid + }, + false, + index, + depth + 1, + serializeFunctions + ); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +}; + +var serializeInto = function serializeInto( + buffer, + object, + checkKeys, + startingIndex, + depth, + serializeFunctions, + ignoreUndefined, + path +) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + true + ); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +// var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/node_modules/bson/lib/bson/parser/utils.js b/node_modules/bson/lib/bson/parser/utils.js new file mode 100644 index 0000000..6b8395f --- /dev/null +++ b/node_modules/bson/lib/bson/parser/utils.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); +} + +module.exports = { + normalizedFunctionString: normalizedFunctionString +}; + diff --git a/node_modules/bson/lib/bson/regexp.js b/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..108f016 --- /dev/null +++ b/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; diff --git a/node_modules/bson/lib/bson/symbol.js b/node_modules/bson/lib/bson/symbol.js index 7681a4d..ba20cab 100644 --- a/node_modules/bson/lib/bson/symbol.js +++ b/node_modules/bson/lib/bson/symbol.js @@ -1,3 +1,6 @@ +// Custom inspect property name / symbol. +var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; + /** * A class representation of the BSON Symbol type. * @@ -7,7 +10,7 @@ * @return {Symbol} */ function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); + if (!(this instanceof Symbol)) return new Symbol(value); this._bsontype = 'Symbol'; this.value = value; } @@ -27,21 +30,21 @@ Symbol.prototype.valueOf = function() { */ Symbol.prototype.toString = function() { return this.value; -} +}; /** * @ignore */ -Symbol.prototype.inspect = function() { +Symbol.prototype[inspect] = function() { return this.value; -} +}; /** * @ignore */ Symbol.prototype.toJSON = function() { return this.value; -} +}; module.exports = Symbol; -module.exports.Symbol = Symbol; \ No newline at end of file +module.exports.Symbol = Symbol; diff --git a/node_modules/bson/lib/bson/timestamp.js b/node_modules/bson/lib/bson/timestamp.js index 7718caf..dc61a6c 100644 --- a/node_modules/bson/lib/bson/timestamp.js +++ b/node_modules/bson/lib/bson/timestamp.js @@ -43,20 +43,20 @@ * @param {number} high the high (signed) 32 bits of the Timestamp. */ function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); + if (!(this instanceof Timestamp)) return new Timestamp(low, high); this._bsontype = 'Timestamp'; /** * @type {number} * @ignore */ - this.low_ = low | 0; // force into 32 signed bits. + this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @ignore */ - this.high_ = high | 0; // force into 32 signed bits. -}; + this.high_ = high | 0; // force into 32 signed bits. +} /** * Return the int value. @@ -74,8 +74,7 @@ Timestamp.prototype.toInt = function() { * @return {number} the closest floating-point representation to this value. */ Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** @@ -86,7 +85,7 @@ Timestamp.prototype.toNumber = function() { */ Timestamp.prototype.toJSON = function() { return this.toString(); -} +}; /** * Return the String value. @@ -122,9 +121,10 @@ Timestamp.prototype.toString = function(opt_radix) { // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - var rem = this; + rem = this; var result = ''; - while (true) { + + while (!rem.isZero()) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); @@ -168,8 +168,7 @@ Timestamp.prototype.getLowBits = function() { * @return {number} the low 32-bits as an unsigned value. */ Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; }; /** @@ -186,13 +185,13 @@ Timestamp.prototype.getNumBitsAbs = function() { return this.negate().getNumBitsAbs(); } } else { - var val = this.high_ != 0 ? this.high_ : this.low_; + var val = this.high_ !== 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { + if ((val & (1 << bit)) !== 0) { break; } } - return this.high_ != 0 ? bit + 33 : bit + 1; + return this.high_ !== 0 ? bit + 33 : bit + 1; } }; @@ -203,7 +202,7 @@ Timestamp.prototype.getNumBitsAbs = function() { * @return {boolean} whether this value is zero. */ Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; + return this.high_ === 0 && this.low_ === 0; }; /** @@ -223,7 +222,7 @@ Timestamp.prototype.isNegative = function() { * @return {boolean} whether this value is odd. */ Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; + return (this.low_ & 1) === 1; }; /** @@ -234,7 +233,7 @@ Timestamp.prototype.isOdd = function() { * @return {boolean} whether this Timestamp equals the other */ Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); + return this.high_ === other.high_ && this.low_ === other.low_; }; /** @@ -245,7 +244,7 @@ Timestamp.prototype.equals = function(other) { * @return {boolean} whether this Timestamp does not equal the other. */ Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); + return this.high_ !== other.high_ || this.low_ !== other.low_; }; /** @@ -346,27 +345,30 @@ 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 a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; + var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; + var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; + var b00 = other.low_ & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; - c00 &= 0xFFFF; + c00 &= 0xffff; c16 += a16 + b16; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c32 += a32 + b32; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c48 += a48 + b48; - c48 &= 0xFFFF; + c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; @@ -405,15 +407,16 @@ Timestamp.prototype.multiply = function(other) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { - return this.negate().multiply(other).negate(); + 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_)) { + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { return Timestamp.fromNumber(this.toNumber() * other.toNumber()); } @@ -421,36 +424,39 @@ Timestamp.prototype.multiply = function(other) { // We can skip products that would overflow. var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; + var a32 = this.high_ & 0xffff; var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; + var a00 = this.low_ & 0xffff; var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; + var b32 = other.high_ & 0xffff; var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; + var b00 = other.low_ & 0xffff; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; - c00 &= 0xFFFF; + c00 &= 0xffff; c16 += a16 * b00; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c16 += a00 * b16; c32 += c16 >>> 16; - c16 &= 0xFFFF; + c16 &= 0xffff; c32 += a32 * b00; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c32 += a16 * b16; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c32 += a00 * b32; c48 += c32 >>> 16; - c32 &= 0xFFFF; + c32 &= 0xffff; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; + c48 &= 0xffff; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; @@ -469,9 +475,8 @@ Timestamp.prototype.div = function(other) { } 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 + 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 { @@ -494,7 +499,9 @@ Timestamp.prototype.div = function(other) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { - return this.negate().div(other).negate(); + return this.negate() + .div(other) + .negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); @@ -506,16 +513,16 @@ Timestamp.prototype.div = function(other) { // 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; + 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())); + 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); + 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. @@ -602,15 +609,13 @@ Timestamp.prototype.xor = function(other) { */ Timestamp.prototype.shiftLeft = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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))); + return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Timestamp.fromBits(0, low << (numBits - 32)); } @@ -626,19 +631,15 @@ Timestamp.prototype.shiftLeft = function(numBits) { */ Timestamp.prototype.shiftRight = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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); + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); + return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; @@ -652,16 +653,14 @@ Timestamp.prototype.shiftRight = function(numBits) { */ Timestamp.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; - if (numBits == 0) { + 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((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { return Timestamp.fromBits(high, 0); } else { return Timestamp.fromBits(high >>> (numBits - 32), 0); @@ -709,8 +708,9 @@ Timestamp.fromNumber = function(value) { return Timestamp.fromNumber(-value).negate(); } else { return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0 + ); } }; @@ -735,7 +735,7 @@ Timestamp.fromBits = function(lowBits, highBits) { * @return {Timestamp} the corresponding Timestamp value. */ Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { + if (str.length === 0) { throw Error('number format error: empty string'); } @@ -744,7 +744,7 @@ Timestamp.fromString = function(str, opt_radix) { throw Error('radix out of range: ' + radix); } - if (str.charAt(0) == '-') { + 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); @@ -772,7 +772,6 @@ Timestamp.fromString = function(str, opt_radix) { // 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} @@ -837,8 +836,7 @@ Timestamp.ONE = Timestamp.fromInt(1); Timestamp.NEG_ONE = Timestamp.fromInt(-1); /** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); +Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); /** @type {Timestamp} */ Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); @@ -853,4 +851,4 @@ Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); * Expose. */ module.exports = Timestamp; -module.exports.Timestamp = Timestamp; \ No newline at end of file +module.exports.Timestamp = Timestamp; diff --git a/node_modules/bson/package.json b/node_modules/bson/package.json index d1e13ed..336cbcd 100644 --- a/node_modules/bson/package.json +++ b/node_modules/bson/package.json @@ -1,27 +1,27 @@ { - "_from": "bson@~0.2", - "_id": "bson@0.2.22", + "_from": "bson@^1.1.0", + "_id": "bson@1.1.0", "_inBundle": false, - "_integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", + "_integrity": "sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA==", "_location": "/bson", "_phantomChildren": {}, "_requested": { "type": "range", "registry": true, - "raw": "bson@~0.2", + "raw": "bson@^1.1.0", "name": "bson", "escapedName": "bson", - "rawSpec": "~0.2", + "rawSpec": "^1.1.0", "saveSpec": null, - "fetchSpec": "~0.2" + "fetchSpec": "^1.1.0" }, "_requiredBy": [ - "/mongodb" + "/mongodb-core" ], - "_resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", - "_shasum": "fcda103f26d0c074d5a52d50927db80fd02b4b39", - "_spec": "bson@~0.2", - "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb", + "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.0.tgz", + "_shasum": "bee57d1fb6a87713471af4e32bcae36de814b5b0", + "_spec": "bson@^1.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb-core", "author": { "name": "Christian Amor Kvalheim", "email": "christkv@gmail.com" @@ -35,15 +35,21 @@ "native": false }, "contributors": [], - "dependencies": { - "nan": "~1.8" - }, "deprecated": false, "description": "A bson parser for node.js and the browser", "devDependencies": { - "gleak": "0.2.3", + "babel-core": "^6.14.0", + "babel-loader": "^6.2.5", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.14.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.14.0", + "benchmark": "1.0.0", + "colors": "1.1.0", + "conventional-changelog-cli": "^1.3.5", "nodeunit": "0.9.0", - "one": "2.X.X" + "webpack": "^1.13.2", + "webpack-polyfills-plugin": "0.0.9" }, "directories": { "lib": "./lib/bson" @@ -51,27 +57,31 @@ "engines": { "node": ">=0.6.19" }, + "files": [ + "lib", + "index.js", + "browser_build", + "bower.json" + ], "homepage": "https://github.com/mongodb/js-bson#readme", "keywords": [ "mongodb", "bson", "parser" ], - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "main": "./lib/bson/index", + "license": "Apache-2.0", + "main": "./index", "name": "bson", "repository": { "type": "git", - "url": "git://github.com/mongodb/js-bson.git" + "url": "git+https://github.com/mongodb/js-bson.git" }, "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" + "build": "webpack --config ./webpack.dist.config.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "lint": "eslint lib test", + "test": "nodeunit ./test/node" }, - "version": "0.2.22" + "version": "1.1.0" } diff --git a/node_modules/express/node_modules/buffer-crc32/.npmignore b/node_modules/buffer-crc32/.npmignore similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/.npmignore rename to node_modules/buffer-crc32/.npmignore diff --git a/node_modules/express/node_modules/buffer-crc32/.travis.yml b/node_modules/buffer-crc32/.travis.yml similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/.travis.yml rename to node_modules/buffer-crc32/.travis.yml diff --git a/node_modules/express/node_modules/buffer-crc32/LICENSE b/node_modules/buffer-crc32/LICENSE similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/LICENSE rename to node_modules/buffer-crc32/LICENSE diff --git a/node_modules/express/node_modules/buffer-crc32/README.md b/node_modules/buffer-crc32/README.md similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/README.md rename to node_modules/buffer-crc32/README.md diff --git a/node_modules/express/node_modules/buffer-crc32/index.js b/node_modules/buffer-crc32/index.js similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/index.js rename to node_modules/buffer-crc32/index.js diff --git a/node_modules/express/node_modules/buffer-crc32/package.json b/node_modules/buffer-crc32/package.json similarity index 70% rename from node_modules/express/node_modules/buffer-crc32/package.json rename to node_modules/buffer-crc32/package.json index b700e32..7fa6c80 100644 --- a/node_modules/express/node_modules/buffer-crc32/package.json +++ b/node_modules/buffer-crc32/package.json @@ -1,56 +1,77 @@ { + "_from": "buffer-crc32@0.2.3", + "_id": "buffer-crc32@0.2.3", + "_inBundle": false, + "_integrity": "sha1-u1RRnpXRB8vSQA520MqxRnM22SE=", + "_location": "/buffer-crc32", + "_npmUser": { + "name": "brianloveswords", + "email": "brianloveswords@gmail.com" + }, + "_npmVersion": "1.4.14", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "buffer-crc32@0.2.3", + "name": "buffer-crc32", + "escapedName": "buffer-crc32", + "rawSpec": "0.2.3", + "saveSpec": null, + "fetchSpec": "0.2.3" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz", + "_shasum": "bb54519e95d107cbd2400e76d0cab1467336d921", + "_spec": "buffer-crc32@0.2.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Brian J. Brennan", "email": "brianloveswords@gmail.com", "url": "http://bjb.io" }, - "name": "buffer-crc32", - "description": "A pure javascript CRC32 algorithm that plays nice with binary data", - "version": "0.2.3", + "bugs": { + "url": "https://github.com/brianloveswords/buffer-crc32/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Vladimir Kuznetsov" } ], - "homepage": "https://github.com/brianloveswords/buffer-crc32", - "repository": { - "type": "git", - "url": "git://github.com/brianloveswords/buffer-crc32.git" - }, - "main": "index.js", - "scripts": { - "test": "tap tests/*.test.js" - }, "dependencies": {}, + "deprecated": false, + "description": "A pure javascript CRC32 algorithm that plays nice with binary data", "devDependencies": { "tap": "~0.2.5" }, - "optionalDependencies": {}, + "directories": {}, + "dist": { + "shasum": "bb54519e95d107cbd2400e76d0cab1467336d921", + "tarball": "http://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz" + }, "engines": { "node": "*" }, "gitHead": "f06dc30bccbad685af30666268c6fd2670805998", - "bugs": { - "url": "https://github.com/brianloveswords/buffer-crc32/issues" - }, - "_id": "buffer-crc32@0.2.3", - "_shasum": "bb54519e95d107cbd2400e76d0cab1467336d921", - "_from": "buffer-crc32@0.2.3", - "_npmVersion": "1.4.14", - "_npmUser": { - "name": "brianloveswords", - "email": "brianloveswords@gmail.com" - }, + "homepage": "https://github.com/brianloveswords/buffer-crc32", + "main": "index.js", "maintainers": [ { "name": "brianloveswords", "email": "brian@nyhacker.org" } ], - "dist": { - "shasum": "bb54519e95d107cbd2400e76d0cab1467336d921", - "tarball": "http://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz" + "name": "buffer-crc32", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/buffer-crc32.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz" + "scripts": { + "test": "tap tests/*.test.js" + }, + "version": "0.2.3" } diff --git a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js b/node_modules/buffer-crc32/tests/crc.test.js similarity index 100% rename from node_modules/express/node_modules/buffer-crc32/tests/crc.test.js rename to node_modules/buffer-crc32/tests/crc.test.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/LICENSE b/node_modules/circular-json/LICENSE.txt similarity index 94% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/LICENSE rename to node_modules/circular-json/LICENSE.txt index 451fc45..e42a04b 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/LICENSE +++ b/node_modules/circular-json/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2010 Benjamin Thomas, Robert Kieffer +Copyright (C) 2013-2017 by Andrea Giammarchi - @WebReflection Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/node_modules/circular-json/README.md b/node_modules/circular-json/README.md new file mode 100644 index 0000000..e6451b2 --- /dev/null +++ b/node_modules/circular-json/README.md @@ -0,0 +1,146 @@ +CircularJSON +============ + +[![donate](https://img.shields.io/badge/$-donate-ff69b4.svg?maxAge=2592000&style=flat)](https://github.com/WebReflection/donate) ![Downloads](https://img.shields.io/npm/dm/circular-json.svg) [![Build Status](https://travis-ci.org/WebReflection/circular-json.svg?branch=master)](https://travis-ci.org/WebReflection/circular-json) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/circular-json/badge.svg?branch=master)](https://coveralls.io/github/WebReflection/circular-json?branch=master) + +Serializes and deserializes otherwise valid JSON objects containing circular references into and from a specialized JSON format. + +- - - + +## The future of this module is called [flatted](https://github.com/WebReflection/flatted#flatted) + +Smaller, faster, and able to produce on average a reduced output too, [flatted](https://github.com/WebReflection/flatted#flatted) is the new, bloatless, ESM and CJS compatible, circular JSON parser. + +It has now reached V1 and it implements the exact same JSON API. + +Please note **CircularJSON is in maintenance only** and **[flatted](https://github.com/WebReflection/flatted#flatted) is its successor**. + +- - - + +### A Working Solution To A Common Problem +A usage example: + +```JavaScript +var object = {}; +object.arr = [ + object, object +]; +object.arr.push(object.arr); +object.obj = object; + +var serialized = CircularJSON.stringify(object); +// '{"arr":["~","~","~arr"],"obj":"~"}' +// NOTE: CircularJSON DOES NOT parse JS +// it handles receiver and reviver callbacks + +var unserialized = CircularJSON.parse(serialized); +// { arr: [ [Circular], [Circular] ], +// obj: [Circular] } + +unserialized.obj === unserialized; +unserialized.arr[0] === unserialized; +unserialized.arr.pop() === unserialized.arr; +``` + +A quick summary: + + * **new** in version `0.5`, you can specify a JSON parser different from JSON itself. `CircularJSON.parser = ABetterJSON;` is all you need. + * uses `~` as a special prefix symbol to denote which parent the reference belongs to (i.e. `~root~child1~child2`) + * reasonably fast in both serialization and deserialization + * compact serialization for easier and slimmer transportation across environments + * [tested and covered](test/circular-json.js) over nasty structures too + * compatible with all JavaScript engines + +Node Installation & Usage +============ + +```bash +npm install --save circular-json +``` + +```javascript +'use strict'; + +var + CircularJSON = require('circular-json'), + obj = { foo: 'bar' }, + str +; + +obj.self = obj; +str = CircularJSON.stringify(obj); +``` + +There are no dependencies. + +Browser Installation & Usage +================ + +* Global: +* AMD: +* CommonJS: + +(generated via [gitstrap](https://github.com/WebReflection/gitstrap)) + +```html + +``` + +```javascript +'use strict'; + +var CircularJSON = window.CircularJSON + , obj = { foo: 'bar' } + , str + ; + +obj.self = obj; +str = CircularJSON.stringify(obj); +``` + +NOTE: Platforms without native JSON (i.e. MSIE <= 8) requires `json3.js` or similar. + +It is also *a bad idea* to `CircularJSON.parse(JSON.stringify(object))` because of those manipulation used in `CircularJSON.stringify()` able to make parsing safe and secure. + +As summary: `CircularJSON.parse(CircularJSON.stringify(object))` is the way to go, same is for `JSON.parse(JSON.stringify(object))`. + +API +=== + +It's the same as native JSON, except the fourth parameter `placeholder`, which circular references to be replaced with `"[Circular]"` (i.e. for logging). + +* CircularJSON.stringify(object, replacer, spacer, placeholder) +* CircularJSON.parse(string, reviver) + +Bear in mind `JSON.parse(CircularJSON.stringify(object))` will work but not produce the expected output. + +Similar Libraries +======= + +### Why Not the [@izs](https://twitter.com/izs) One +The module [json-stringify-safe](https://github.com/isaacs/json-stringify-safe) seems to be for `console.log()` but it's completely pointless for `JSON.parse()`, being latter one unable to retrieve back the initial structure. Here an example: + +```JavaScript +// a logged object with circular references +{ + "circularRef": "[Circular]", + "list": [ + "[Circular]", + "[Circular]" + ] +} +// what do we do with above output ? +``` + +Just type this in your `node` console: `var o = {}; o.a = o; console.log(o);`. The output will be `{ a: [Circular] }` ... good, but that ain't really solving the problem. + +However, if that's all you need, the function used to create that kind of output is probably faster than `CircularJSON` and surely fits in less lines of code. + + +### Why Not {{put random name}} Solution +So here the thing: circular references can be wrong but, if there is a need for them, any attempt to ignore them or remove them can be considered just a failure. + +Not because the method is bad or it's not working, simply because the circular info, the one we needed and used in the first place, is lost! + +In this case, `CircularJSON` does even more than just solve circular and recursions: it maps all same objects so that less memory is used as well on deserialization as less bandwidth too! +It's able to redefine those references back later on so the way we store is the way we retrieve and in a reasonably performant way, also trusting the snappy and native `JSON` methods to iterate. diff --git a/node_modules/circular-json/build/circular-json.js b/node_modules/circular-json/build/circular-json.js new file mode 100644 index 0000000..bcb6046 --- /dev/null +++ b/node_modules/circular-json/build/circular-json.js @@ -0,0 +1,2 @@ +/*! (C) WebReflection Mit Style License */ +var CircularJSON=function(JSON,RegExp){var specialChar="~",safeSpecialChar="\\x"+("0"+specialChar.charCodeAt(0).toString(16)).slice(-2),escapedSafeSpecialChar="\\"+safeSpecialChar,specialCharRG=new RegExp(safeSpecialChar,"g"),safeSpecialCharRG=new RegExp(escapedSafeSpecialChar,"g"),safeStartWithSpecialCharRG=new RegExp("(?:^|([^\\\\]))"+escapedSafeSpecialChar),indexOf=[].indexOf||function(v){for(var i=this.length;i--&&this[i]!==v;);return i},$String=String;function generateReplacer(value,replacer,resolve){var doNotIgnore=false,inspect=!!replacer,path=[],all=[value],seen=[value],mapp=[resolve?specialChar:"[Circular]"],last=value,lvl=1,i,fn;if(inspect){fn=typeof replacer==="object"?function(key,value){return key!==""&&replacer.indexOf(key)<0?void 0:value}:replacer}return function(key,value){if(inspect)value=fn.call(this,key,value);if(doNotIgnore){if(last!==this){i=lvl-indexOf.call(all,this)-1;lvl-=i;all.splice(lvl,all.length);path.splice(lvl-1,path.length);last=this}if(typeof value==="object"&&value){if(indexOf.call(all,value)<0){all.push(last=value)}lvl=all.length;i=indexOf.call(seen,value);if(i<0){i=seen.push(value)-1;if(resolve){path.push((""+key).replace(specialCharRG,safeSpecialChar));mapp[i]=specialChar+path.join(specialChar)}else{mapp[i]=mapp[0]}}else{value=mapp[i]}}else{if(typeof value==="string"&&resolve){value=value.replace(safeSpecialChar,escapedSafeSpecialChar).replace(specialChar,safeSpecialChar)}}}else{doNotIgnore=true}return value}}function retrieveFromPath(current,keys){for(var i=0,length=keys.length;i= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter spec --bail --require should test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" - }, - "bugs": { - "url": "https://github.com/dougwilson/nodejs-depd/issues" - }, - "homepage": "https://github.com/dougwilson/nodejs-depd", - "_id": "depd@0.3.0", + "directories": {}, "dist": { "shasum": "11c9bc28e425325fbd8b38940beff69fa5326883", "tarball": "http://registry.npmjs.org/depd/-/depd-0.3.0.tgz" }, - "_from": "depd@0.3.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/dougwilson/nodejs-depd", + "keywords": [ + "deprecate", + "deprecated" + ], + "license": "MIT", "maintainers": [ { "name": "dougwilson", "email": "doug@somethingdoug.com" } ], - "directories": {}, - "_shasum": "11c9bc28e425325fbd8b38940beff69fa5326883", - "_resolved": "https://registry.npmjs.org/depd/-/depd-0.3.0.tgz" + "name": "depd", + "repository": { + "type": "git", + "url": "git://github.com/dougwilson/nodejs-depd.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --require should test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" + }, + "version": "0.3.0" } diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/.npmignore b/node_modules/ee-first/.npmignore similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/.npmignore rename to node_modules/ee-first/.npmignore diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE b/node_modules/ee-first/LICENSE similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/LICENSE rename to node_modules/ee-first/LICENSE diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/README.md b/node_modules/ee-first/README.md similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/README.md rename to node_modules/ee-first/README.md diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/index.js b/node_modules/ee-first/index.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/index.js rename to node_modules/ee-first/index.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/package.json b/node_modules/ee-first/package.json similarity index 65% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/package.json rename to node_modules/ee-first/package.json index 8889099..85a2e9c 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/package.json +++ b/node_modules/ee-first/package.json @@ -1,35 +1,53 @@ { - "name": "ee-first", - "description": "return the first event in a set of ee/event pairs", - "version": "1.0.3", + "_from": "ee-first@1.0.3", + "_id": "ee-first@1.0.3", + "_inBundle": false, + "_integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=", + "_location": "/ee-first", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "_npmVersion": "1.4.9", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ee-first@1.0.3", + "name": "ee-first", + "escapedName": "ee-first", + "rawSpec": "1.0.3", + "saveSpec": null, + "fetchSpec": "1.0.3" + }, + "_requiredBy": [ + "/finished" + ], + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", + "_shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", + "_spec": "ee-first@1.0.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\finished", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/jonathanong/ee-first" + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" }, + "bundleDependencies": false, + "deprecated": false, + "description": "return the first event in a set of ee/event pairs", "devDependencies": { "mocha": "1" }, - "scripts": { - "test": "mocha --reporter spec" - }, - "bugs": { - "url": "https://github.com/jonathanong/ee-first/issues" + "directories": {}, + "dist": { + "shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", + "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz" }, "homepage": "https://github.com/jonathanong/ee-first", - "_id": "ee-first@1.0.3", - "_shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", - "_from": "ee-first@1.0.3", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, + "license": "MIT", "maintainers": [ { "name": "jongleberry", @@ -40,10 +58,13 @@ "email": "doug@somethingdoug.com" } ], - "dist": { - "shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", - "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz" + "name": "ee-first", + "repository": { + "type": "git", + "url": "git://github.com/jonathanong/ee-first.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz" + "scripts": { + "test": "mocha --reporter spec" + }, + "version": "1.0.3" } diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/test.js b/node_modules/ee-first/test.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/test.js rename to node_modules/ee-first/test.js diff --git a/node_modules/express/node_modules/escape-html/.npmignore b/node_modules/escape-html/.npmignore similarity index 100% rename from node_modules/express/node_modules/escape-html/.npmignore rename to node_modules/escape-html/.npmignore diff --git a/node_modules/express/node_modules/escape-html/Makefile b/node_modules/escape-html/Makefile similarity index 100% rename from node_modules/express/node_modules/escape-html/Makefile rename to node_modules/escape-html/Makefile diff --git a/node_modules/express/node_modules/escape-html/Readme.md b/node_modules/escape-html/Readme.md similarity index 100% rename from node_modules/express/node_modules/escape-html/Readme.md rename to node_modules/escape-html/Readme.md diff --git a/node_modules/express/node_modules/escape-html/component.json b/node_modules/escape-html/component.json similarity index 100% rename from node_modules/express/node_modules/escape-html/component.json rename to node_modules/escape-html/component.json diff --git a/node_modules/express/node_modules/escape-html/index.js b/node_modules/escape-html/index.js similarity index 100% rename from node_modules/express/node_modules/escape-html/index.js rename to node_modules/escape-html/index.js diff --git a/node_modules/express/node_modules/escape-html/package.json b/node_modules/escape-html/package.json similarity index 57% rename from node_modules/express/node_modules/escape-html/package.json rename to node_modules/escape-html/package.json index 7f0b109..014cf6c 100644 --- a/node_modules/express/node_modules/escape-html/package.json +++ b/node_modules/escape-html/package.json @@ -1,45 +1,70 @@ { - "name": "escape-html", - "description": "Escape HTML entities", - "version": "1.0.1", - "keywords": [ - "escape", - "html", - "utility" + "_from": "escape-html@1.0.1", + "_id": "escape-html@1.0.1", + "_inBundle": false, + "_integrity": "sha1-GBoobq05ejmpKFfPsdQwUuNWv/A=", + "_location": "/escape-html", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "_npmVersion": "1.3.15", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "escape-html@1.0.1", + "name": "escape-html", + "escapedName": "escape-html", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express", + "/finalhandler", + "/send", + "/serve-static", + "/serve-static/send" ], - "dependencies": {}, - "main": "index.js", + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz", + "_shasum": "181a286ead397a39a92857cfb1d43052e356bff0", + "_spec": "escape-html@1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "escape-html/index.js": "index.js" } }, - "repository": { - "type": "git", - "url": "https://github.com/component/escape-html.git" - }, - "bugs": { - "url": "https://github.com/component/escape-html/issues" - }, - "homepage": "https://github.com/component/escape-html", - "_id": "escape-html@1.0.1", + "dependencies": {}, + "deprecated": false, + "description": "Escape HTML entities", + "directories": {}, "dist": { "shasum": "181a286ead397a39a92857cfb1d43052e356bff0", "tarball": "http://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" }, - "_from": "escape-html@1.0.1", - "_npmVersion": "1.3.15", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, + "homepage": "https://github.com/component/escape-html", + "keywords": [ + "escape", + "html", + "utility" + ], + "main": "index.js", "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "181a286ead397a39a92857cfb1d43052e356bff0", - "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz" + "name": "escape-html", + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "version": "1.0.1" } diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json b/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json deleted file mode 100644 index 10a028c..0000000 --- a/node_modules/express/node_modules/accepts/node_modules/mime-types/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "mime-types", - "description": "The ultimate javascript content-type utility.", - "version": "1.0.2", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "contributors": [ - { - "name": "Jeremiah Senkpiel", - "email": "fishrock123@rocketmail.com", - "url": "https://searchbeam.jit.su" - } - ], - "repository": { - "type": "git", - "url": "https://github.com/expressjs/mime-types" - }, - "license": "MIT", - "main": "lib", - "devDependencies": { - "co": "3", - "cogent": "0", - "mocha": "1", - "should": "3" - }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "make test" - }, - "gitHead": "e82b23836eb42003b8346fb31769da2fb7eb54e8", - "bugs": { - "url": "https://github.com/expressjs/mime-types/issues" - }, - "homepage": "https://github.com/expressjs/mime-types", - "_id": "mime-types@1.0.2", - "_shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", - "_from": "mime-types@>=1.0.1 <1.1.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", - "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" -} diff --git a/node_modules/express/node_modules/debug/node_modules/ms/.npmignore b/node_modules/express/node_modules/ms/.npmignore similarity index 100% rename from node_modules/express/node_modules/debug/node_modules/ms/.npmignore rename to node_modules/express/node_modules/ms/.npmignore diff --git a/node_modules/express/node_modules/debug/node_modules/ms/README.md b/node_modules/express/node_modules/ms/README.md similarity index 100% rename from node_modules/express/node_modules/debug/node_modules/ms/README.md rename to node_modules/express/node_modules/ms/README.md diff --git a/node_modules/express/node_modules/debug/node_modules/ms/index.js b/node_modules/express/node_modules/ms/index.js similarity index 100% rename from node_modules/express/node_modules/debug/node_modules/ms/index.js rename to node_modules/express/node_modules/ms/index.js diff --git a/node_modules/express/node_modules/send/node_modules/ms/package.json b/node_modules/express/node_modules/ms/package.json similarity index 55% rename from node_modules/express/node_modules/send/node_modules/ms/package.json rename to node_modules/express/node_modules/ms/package.json index 887c7ef..7fd797f 100644 --- a/node_modules/express/node_modules/send/node_modules/ms/package.json +++ b/node_modules/express/node_modules/ms/package.json @@ -1,44 +1,65 @@ { - "name": "ms", - "version": "0.6.2", - "description": "Tiny ms conversion utility", - "repository": { - "type": "git", - "url": "git://github.com/guille/ms.js.git" + "_from": "ms@0.6.2", + "_id": "ms@0.6.2", + "_inBundle": false, + "_integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=", + "_location": "/express/ms", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" }, - "main": "./index", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" + "_npmVersion": "1.2.30", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.6.2", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.6.2", + "saveSpec": null, + "fetchSpec": "0.6.2" }, + "_requiredBy": [ + "/express/debug" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", + "_spec": "ms@0.6.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express\\node_modules\\debug", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "ms/index.js": "index.js" } }, - "bugs": { - "url": "https://github.com/guille/ms.js/issues" + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" }, - "_id": "ms@0.6.2", + "directories": {}, "dist": { "shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", "tarball": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz" }, - "_from": "ms@0.6.2", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, + "homepage": "https://github.com/guille/ms.js#readme", + "main": "./index", "maintainers": [ { "name": "rauchg", "email": "rauchg@gmail.com" } ], - "directories": {}, - "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "scripts": {} + "name": "ms", + "repository": { + "type": "git", + "url": "git://github.com/guille/ms.js.git" + }, + "version": "0.6.2" } diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/package.json b/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/package.json deleted file mode 100644 index 8889099..0000000 --- a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/package.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "name": "ee-first", - "description": "return the first event in a set of ee/event pairs", - "version": "1.0.3", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/jonathanong/ee-first" - }, - "devDependencies": { - "mocha": "1" - }, - "scripts": { - "test": "mocha --reporter spec" - }, - "bugs": { - "url": "https://github.com/jonathanong/ee-first/issues" - }, - "homepage": "https://github.com/jonathanong/ee-first", - "_id": "ee-first@1.0.3", - "_shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", - "_from": "ee-first@1.0.3", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - } - ], - "dist": { - "shasum": "6c98c4089abecb5a7b85c1ac449aa603d3b3dabe", - "tarball": "http://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz" -} diff --git a/node_modules/express/node_modules/send/node_modules/finished/package.json b/node_modules/express/node_modules/send/node_modules/finished/package.json deleted file mode 100644 index 2ef2522..0000000 --- a/node_modules/express/node_modules/send/node_modules/finished/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "name": "finished", - "description": "Execute a callback when a request closes, finishes, or errors", - "version": "1.2.2", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/finished" - }, - "dependencies": { - "ee-first": "1.0.3" - }, - "devDependencies": { - "istanbul": "0.2.10", - "mocha": "~1.20.1", - "should": "~4.0.1" - }, - "engine": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter spec test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/finished/issues" - }, - "homepage": "https://github.com/expressjs/finished", - "_id": "finished@1.2.2", - "_shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", - "_from": "finished@1.2.2", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - "maintainers": [ - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "mscdex", - "email": "mscdex@mscdex.net" - }, - { - "name": "fishrock123", - "email": "fishrock123@rocketmail.com" - } - ], - "dist": { - "shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", - "tarball": "http://registry.npmjs.org/finished/-/finished-1.2.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz" -} diff --git a/node_modules/express/node_modules/send/node_modules/mime/package.json b/node_modules/express/node_modules/send/node_modules/mime/package.json deleted file mode 100644 index 3ab7acc..0000000 --- a/node_modules/express/node_modules/send/node_modules/mime/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "author": { - "name": "Robert Kieffer", - "email": "robert@broofa.com", - "url": "http://github.com/broofa" - }, - "contributors": [ - { - "name": "Benjamin Thomas", - "email": "benjamin@benjaminthomas.org", - "url": "http://github.com/bentomas" - } - ], - "dependencies": {}, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": {}, - "keywords": [ - "util", - "mime" - ], - "main": "mime.js", - "name": "mime", - "repository": { - "url": "https://github.com/broofa/node-mime", - "type": "git" - }, - "version": "1.2.11", - "bugs": { - "url": "https://github.com/broofa/node-mime/issues" - }, - "_id": "mime@1.2.11", - "dist": { - "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" - }, - "_from": "mime@1.2.11", - "_npmVersion": "1.3.6", - "_npmUser": { - "name": "broofa", - "email": "robert@broofa.com" - }, - "maintainers": [ - { - "name": "broofa", - "email": "robert@broofa.com" - }, - { - "name": "bentomas", - "email": "benjamin@benjaminthomas.org" - } - ], - "directories": {}, - "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz" -} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/HISTORY.md b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/HISTORY.md deleted file mode 100644 index 8937250..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/HISTORY.md +++ /dev/null @@ -1,50 +0,0 @@ -1.2.2 / 2014-06-10 -========== - - * reduce listeners added to emitters - - avoids "event emitter leak" warnings when used multiple times on same request - -1.2.1 / 2014-06-08 -================== - - * fix returned value when already finished - -1.2.0 / 2014-06-05 -================== - - * call callback when called on already-finished socket - -1.1.4 / 2014-05-27 -================== - - * support node.js 0.8 - -1.1.3 / 2014-04-30 -================== - - * make sure errors passed as instanceof `Error` - -1.1.2 / 2014-04-18 -================== - - * default the `socket` to passed-in object - -1.1.1 / 2014-01-16 -================== - - * rename module to `finished` - -1.1.0 / 2013-12-25 -================== - - * call callback when called on already-errored socket - -1.0.1 / 2013-12-20 -================== - - * actually pass the error to the callback - -1.0.0 / 2013-12-20 -================== - - * Initial release diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/README.md b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/README.md deleted file mode 100644 index 79facd5..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# finished - -[![NPM Version](https://badge.fury.io/js/finished.svg)](http://badge.fury.io/js/finished) -[![Build Status](https://travis-ci.org/expressjs/finished.svg?branch=master)](https://travis-ci.org/expressjs/finished) -[![Coverage Status](https://img.shields.io/coveralls/expressjs/finished.svg?branch=master)](https://coveralls.io/r/expressjs/finished) - -Execute a callback when a request closes, finishes, or errors. - -#### Install - -```sh -$ npm install finished -``` - -#### Uses - -This is useful for cleaning up streams. For example, you want to destroy any file streams you create on socket errors otherwise you will leak file descriptors. - -This is required to fix what many perceive as issues with node's streams. Relevant: - -- [node#6041](https://github.com/joyent/node/issues/6041) -- [koa#184](https://github.com/koajs/koa/issues/184) -- [koa#165](https://github.com/koajs/koa/issues/165) - -## API - -### finished(response, callback) - -```js -var onFinished = require('finished') - -onFinished(res, function (err) { - // do something maybe -}) -``` - -### Examples - -The following code ensures that file descriptors are always closed once the response finishes. - -#### Node / Connect / Express - -```js -var onFinished = require('finished') - -function (req, res, next) { - var stream = fs.createReadStream('thingie.json') - stream.pipe(res) - onFinished(res, function (err) { - stream.destroy() - }) -} -``` - -#### Koa - -```js -function* () { - var stream = this.body = fs.createReadStream('thingie.json') - onFinished(this, function (err) { - stream.destroy() - }) -} -``` - -## License - -The MIT License (MIT) - -Copyright (c) 2013 Jonathan Ong me@jongleberry.com - -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. diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/index.js b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/index.js deleted file mode 100644 index 90709d4..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/*! - * finished - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** -* Module dependencies. -*/ - -var first = require('ee-first') - -/** -* Variables. -*/ - -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } - -/** - * Invoke callback when the response has finished, useful for - * cleaning up resources afterwards. - * - * @param {object} thingie - * @param {function} callback - * @return {object} - * @api public - */ - -module.exports = function finished(thingie, callback) { - var socket = thingie.socket || thingie - var res = thingie.res || thingie - - if (res.finished || !socket.writable) { - defer(callback) - return thingie - } - - var listener = res.__onFinished - - // create a private single listener with queue - if (!listener || !listener.queue) { - listener = res.__onFinished = function onFinished(err) { - if (res.__onFinished === listener) res.__onFinished = null - var queue = listener.queue || [] - while (queue.length) queue.shift()(err) - } - listener.queue = [] - - // finished on first event - first([ - [socket, 'error', 'close'], - [res, 'finish'], - ], listener) - } - - listener.queue.push(callback) - - return thingie -} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/README.md b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/README.md deleted file mode 100644 index 7eae173..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/README.md +++ /dev/null @@ -1,5 +0,0 @@ - -# EE First - -Get the first event in a set of event emitters and event pairs, -then clean up after itself. diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/index.js b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/index.js deleted file mode 100644 index d0c48c9..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/index.js +++ /dev/null @@ -1,60 +0,0 @@ - -module.exports = function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') - - var cleanups = [] - - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] - - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') - - var ee = arr[0] - - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, cleanup) - - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } - - return function (fn) { - done = fn - } - - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) - } - done.apply(null, arguments) - } -} - -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null - - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - - done(err, ee, event, args) - } -} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/test.js b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/test.js deleted file mode 100644 index adff984..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/test.js +++ /dev/null @@ -1,60 +0,0 @@ - -var EventEmitter = require('events').EventEmitter -var assert = require('assert') - -var first = require('./') - -describe('first', function () { - var ee1 = new EventEmitter() - var ee2 = new EventEmitter() - var ee3 = new EventEmitter() - - it('should emit the first event', function (done) { - first([ - [ee1, 'a', 'b', 'c'], - [ee2, 'a', 'b', 'c'], - [ee3, 'a', 'b', 'c'], - ], function (err, ee, event, args) { - assert.ifError(err) - assert.equal(ee, ee2) - assert.equal(event, 'b') - assert.deepEqual(args, [1, 2, 3]) - done() - }) - - ee2.emit('b', 1, 2, 3) - }) - - it('it should return an error if event === error', function (done) { - first([ - [ee1, 'error', 'b', 'c'], - [ee2, 'error', 'b', 'c'], - [ee3, 'error', 'b', 'c'], - ], function (err, ee, event, args) { - assert.equal(err.message, 'boom') - assert.equal(ee, ee3) - assert.equal(event, 'error') - done() - }) - - ee3.emit('error', new Error('boom')) - }) - - it('should cleanup after itself', function (done) { - first([ - [ee1, 'a', 'b', 'c'], - [ee2, 'a', 'b', 'c'], - [ee3, 'a', 'b', 'c'], - ], function (err, ee, event, args) { - assert.ifError(err) - ;[ee1, ee2, ee3].forEach(function (ee) { - ['a', 'b', 'c'].forEach(function (event) { - assert(!ee.listeners(event).length) - }) - }) - done() - }) - - ee1.emit('a') - }) -}) diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/README.md b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/README.md deleted file mode 100644 index 6ca19bd..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# mime - -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - - var mime = require('mime'); - - mime.lookup('/path/to/file.txt'); // => 'text/plain' - mime.lookup('file.txt'); // => 'text/plain' - mime.lookup('.TXT'); // => 'text/plain' - mime.lookup('htm'); // => 'text/html' - -### mime.default_type -Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) - -### mime.extension(type) -Get the default extension for `type` - - mime.extension('text/html'); // => 'html' - mime.extension('application/octet-stream'); // => 'bin' - -### mime.charsets.lookup() - -Map mime-type to charset - - mime.charsets.lookup('text/plain'); // => 'UTF-8' - -(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) - -## API - Defining Custom Types - -The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). - -### mime.define() - -Add custom mime/extension mappings - - mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... - }); - - mime.lookup('x-sft'); // => 'text/x-some-format' - -The first entry in the extensions array is returned by `mime.extension()`. E.g. - - mime.extension('text/x-some-format'); // => 'x-sf' - -### mime.load(filepath) - -Load mappings from an Apache ".types" format file - - mime.load('./my_project.types'); - -The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/mime.js b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/mime.js deleted file mode 100644 index 48be0c5..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/mime.js +++ /dev/null @@ -1,114 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); - - // Map of mime type -> extension - this.extensions = Object.create(null); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts]) { - console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts] + ' to ' + type); - } - - this.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; - -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); - - this._loading = null; -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); - - return this.types[ext] || fallback || this.default_type; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; - -// Default instance -var mime = new Mime(); - -// Load local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Load additional types from node.js community -mime.load(path.join(__dirname, 'types/node.types')); - -// Default type -mime.default_type = mime.lookup('bin'); - -// -// Additional API specific to the default instance -// - -mime.Mime = Mime; - -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } -}; - -module.exports = mime; diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/test.js b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/test.js deleted file mode 100644 index 2cda1c7..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/test.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('./mime'); -var assert = require('assert'); -var path = require('path'); - -function eq(a, b) { - console.log('Test: ' + a + ' === ' + b); - assert.strictEqual.apply(null, arguments); -} - -console.log(Object.keys(mime.extensions).length + ' types'); -console.log(Object.keys(mime.types).length + ' extensions\n'); - -// -// Test mime lookups -// - -eq('text/plain', mime.lookup('text.txt')); // normal file -eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase -eq('text/plain', mime.lookup('dir/text.txt')); // dir + file -eq('text/plain', mime.lookup('.text.txt')); // hidden file -eq('text/plain', mime.lookup('.txt')); // nameless -eq('text/plain', mime.lookup('txt')); // extension-only -eq('text/plain', mime.lookup('/txt')); // extension-less () -eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less -eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized -eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default - -// -// Test extensions -// - -eq('txt', mime.extension(mime.types.text)); -eq('html', mime.extension(mime.types.htm)); -eq('bin', mime.extension('application/octet-stream')); -eq('bin', mime.extension('application/octet-stream ')); -eq('html', mime.extension(' text/html; charset=UTF-8')); -eq('html', mime.extension('text/html; charset=UTF-8 ')); -eq('html', mime.extension('text/html; charset=UTF-8')); -eq('html', mime.extension('text/html ; charset=UTF-8')); -eq('html', mime.extension('text/html;charset=UTF-8')); -eq('html', mime.extension('text/Html;charset=UTF-8')); -eq(undefined, mime.extension('unrecognized')); - -// -// Test node.types lookups -// - -eq('application/font-woff', mime.lookup('file.woff')); -eq('application/octet-stream', mime.lookup('file.buffer')); -eq('audio/mp4', mime.lookup('file.m4a')); -eq('font/opentype', mime.lookup('file.otf')); - -// -// Test charsets -// - -eq('UTF-8', mime.charsets.lookup('text/plain')); -eq(undefined, mime.charsets.lookup(mime.types.js)); -eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -// -// Test for overlaps between mime.types and node.types -// - -var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); -apacheTypes.load(path.join(__dirname, 'types/mime.types')); -nodeTypes.load(path.join(__dirname, 'types/node.types')); - -var keys = [].concat(Object.keys(apacheTypes.types)) - .concat(Object.keys(nodeTypes.types)); -keys.sort(); -for (var i = 1; i < keys.length; i++) { - if (keys[i] == keys[i-1]) { - console.warn('Warning: ' + - 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + - ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); - } -} - -console.log('\nOK'); diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/mime.types b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/mime.types deleted file mode 100644 index da8cd69..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/mime.types +++ /dev/null @@ -1,1588 +0,0 @@ -# This file maps Internet media types to unique file extension(s). -# Although created for httpd, this file is used by many software systems -# and has been placed in the public domain for unlimited redisribution. -# -# The table below contains both registered and (common) unregistered types. -# A type that has no unique extension can be ignored -- they are listed -# here to guide configurations toward known types and to make it easier to -# identify "new" types. File extensions are also commonly used to indicate -# content languages and encodings, so choose them carefully. -# -# Internet media types should be registered as described in RFC 4288. -# The registry is at . -# -# MIME type (lowercased) Extensions -# ============================================ ========== -# application/1d-interleaved-parityfec -# application/3gpp-ims+xml -# application/activemessage -application/andrew-inset ez -# application/applefile -application/applixware aw -application/atom+xml atom -application/atomcat+xml atomcat -# application/atomicmail -application/atomsvc+xml atomsvc -# application/auth-policy+xml -# application/batch-smtp -# application/beep+xml -# application/calendar+xml -# application/cals-1840 -# application/ccmp+xml -application/ccxml+xml ccxml -application/cdmi-capability cdmia -application/cdmi-container cdmic -application/cdmi-domain cdmid -application/cdmi-object cdmio -application/cdmi-queue cdmiq -# application/cea-2018+xml -# application/cellml+xml -# application/cfw -# application/cnrp+xml -# application/commonground -# application/conference-info+xml -# application/cpl+xml -# application/csta+xml -# application/cstadata+xml -application/cu-seeme cu -# application/cybercash -application/davmount+xml davmount -# application/dca-rft -# application/dec-dx -# application/dialog-info+xml -# application/dicom -# application/dns -application/docbook+xml dbk -# application/dskpp+xml -application/dssc+der dssc -application/dssc+xml xdssc -# application/dvcs -application/ecmascript ecma -# application/edi-consent -# application/edi-x12 -# application/edifact -application/emma+xml emma -# application/epp+xml -application/epub+zip epub -# application/eshop -# application/example -application/exi exi -# application/fastinfoset -# application/fastsoap -# application/fits -application/font-tdpfr pfr -# application/framework-attributes+xml -application/gml+xml gml -application/gpx+xml gpx -application/gxf gxf -# application/h224 -# application/held+xml -# application/http -application/hyperstudio stk -# application/ibe-key-request+xml -# application/ibe-pkg-reply+xml -# application/ibe-pp-data -# application/iges -# application/im-iscomposing+xml -# application/index -# application/index.cmd -# application/index.obj -# application/index.response -# application/index.vnd -application/inkml+xml ink inkml -# application/iotp -application/ipfix ipfix -# application/ipp -# application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/javascript js -application/json json -application/jsonml+json jsonml -# application/kpml-request+xml -# application/kpml-response+xml -application/lost+xml lostxml -application/mac-binhex40 hqx -application/mac-compactpro cpt -# application/macwriteii -application/mads+xml mads -application/marc mrc -application/marcxml+xml mrcx -application/mathematica ma nb mb -# application/mathml-content+xml -# application/mathml-presentation+xml -application/mathml+xml mathml -# application/mbms-associated-procedure-description+xml -# application/mbms-deregister+xml -# application/mbms-envelope+xml -# application/mbms-msk+xml -# application/mbms-msk-response+xml -# application/mbms-protection-description+xml -# application/mbms-reception-report+xml -# application/mbms-register+xml -# application/mbms-register-response+xml -# application/mbms-user-service-description+xml -application/mbox mbox -# application/media_control+xml -application/mediaservercontrol+xml mscml -application/metalink+xml metalink -application/metalink4+xml meta4 -application/mets+xml mets -# application/mikey -application/mods+xml mods -# application/moss-keys -# application/moss-signature -# application/mosskey-data -# application/mosskey-request -application/mp21 m21 mp21 -application/mp4 mp4s -# application/mpeg4-generic -# application/mpeg4-iod -# application/mpeg4-iod-xmt -# application/msc-ivr+xml -# application/msc-mixer+xml -application/msword doc dot -application/mxf mxf -# application/nasdata -# application/news-checkgroups -# application/news-groupinfo -# application/news-transmission -# application/nss -# application/ocsp-request -# application/ocsp-response -application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy -application/oda oda -application/oebps-package+xml opf -application/ogg ogx -application/omdoc+xml omdoc -application/onenote onetoc onetoc2 onetmp onepkg -application/oxps oxps -# application/parityfec -application/patch-ops-error+xml xer -application/pdf pdf -application/pgp-encrypted pgp -# application/pgp-keys -application/pgp-signature asc sig -application/pics-rules prf -# application/pidf+xml -# application/pidf-diff+xml -application/pkcs10 p10 -application/pkcs7-mime p7m p7c -application/pkcs7-signature p7s -application/pkcs8 p8 -application/pkix-attr-cert ac -application/pkix-cert cer -application/pkix-crl crl -application/pkix-pkipath pkipath -application/pkixcmp pki -application/pls+xml pls -# application/poc-settings+xml -application/postscript ai eps ps -# application/prs.alvestrand.titrax-sheet -application/prs.cww cww -# application/prs.nprend -# application/prs.plucker -# application/prs.rdf-xml-crypt -# application/prs.xsf+xml -application/pskc+xml pskcxml -# application/qsig -application/rdf+xml rdf -application/reginfo+xml rif -application/relax-ng-compact-syntax rnc -# application/remote-printing -application/resource-lists+xml rl -application/resource-lists-diff+xml rld -# application/riscos -# application/rlmi+xml -application/rls-services+xml rs -application/rpki-ghostbusters gbr -application/rpki-manifest mft -application/rpki-roa roa -# application/rpki-updown -application/rsd+xml rsd -application/rss+xml rss -application/rtf rtf -# application/rtx -# application/samlassertion+xml -# application/samlmetadata+xml -application/sbml+xml sbml -application/scvp-cv-request scq -application/scvp-cv-response scs -application/scvp-vp-request spq -application/scvp-vp-response spp -application/sdp sdp -# application/set-payment -application/set-payment-initiation setpay -# application/set-registration -application/set-registration-initiation setreg -# application/sgml -# application/sgml-open-catalog -application/shf+xml shf -# application/sieve -# application/simple-filter+xml -# application/simple-message-summary -# application/simplesymbolcontainer -# application/slate -# application/smil -application/smil+xml smi smil -# application/soap+fastinfoset -# application/soap+xml -application/sparql-query rq -application/sparql-results+xml srx -# application/spirits-event+xml -application/srgs gram -application/srgs+xml grxml -application/sru+xml sru -application/ssdl+xml ssdl -application/ssml+xml ssml -# application/tamp-apex-update -# application/tamp-apex-update-confirm -# application/tamp-community-update -# application/tamp-community-update-confirm -# application/tamp-error -# application/tamp-sequence-adjust -# application/tamp-sequence-adjust-confirm -# application/tamp-status-query -# application/tamp-status-response -# application/tamp-update -# application/tamp-update-confirm -application/tei+xml tei teicorpus -application/thraud+xml tfi -# application/timestamp-query -# application/timestamp-reply -application/timestamped-data tsd -# application/tve-trigger -# application/ulpfec -# application/vcard+xml -# application/vemmi -# application/vividence.scriptfile -# application/vnd.3gpp.bsf+xml -application/vnd.3gpp.pic-bw-large plb -application/vnd.3gpp.pic-bw-small psb -application/vnd.3gpp.pic-bw-var pvb -# application/vnd.3gpp.sms -# application/vnd.3gpp2.bcmcsinfo+xml -# application/vnd.3gpp2.sms -application/vnd.3gpp2.tcap tcap -application/vnd.3m.post-it-notes pwn -application/vnd.accpac.simply.aso aso -application/vnd.accpac.simply.imp imp -application/vnd.acucobol acu -application/vnd.acucorp atc acutc -application/vnd.adobe.air-application-installer-package+zip air -application/vnd.adobe.formscentral.fcdt fcdt -application/vnd.adobe.fxp fxp fxpl -# application/vnd.adobe.partial-upload -application/vnd.adobe.xdp+xml xdp -application/vnd.adobe.xfdf xfdf -# application/vnd.aether.imp -# application/vnd.ah-barcode -application/vnd.ahead.space ahead -application/vnd.airzip.filesecure.azf azf -application/vnd.airzip.filesecure.azs azs -application/vnd.amazon.ebook azw -application/vnd.americandynamics.acc acc -application/vnd.amiga.ami ami -# application/vnd.amundsen.maze+xml -application/vnd.android.package-archive apk -application/vnd.anser-web-certificate-issue-initiation cii -application/vnd.anser-web-funds-transfer-initiation fti -application/vnd.antix.game-component atx -application/vnd.apple.installer+xml mpkg -application/vnd.apple.mpegurl m3u8 -# application/vnd.arastra.swi -application/vnd.aristanetworks.swi swi -application/vnd.astraea-software.iota iota -application/vnd.audiograph aep -# application/vnd.autopackage -# application/vnd.avistar+xml -application/vnd.blueice.multipass mpm -# application/vnd.bluetooth.ep.oob -application/vnd.bmi bmi -application/vnd.businessobjects rep -# application/vnd.cab-jscript -# application/vnd.canon-cpdl -# application/vnd.canon-lips -# application/vnd.cendio.thinlinc.clientconf -application/vnd.chemdraw+xml cdxml -application/vnd.chipnuts.karaoke-mmd mmd -application/vnd.cinderella cdy -# application/vnd.cirpack.isdn-ext -application/vnd.claymore cla -application/vnd.cloanto.rp9 rp9 -application/vnd.clonk.c4group c4g c4d c4f c4p c4u -application/vnd.cluetrust.cartomobile-config c11amc -application/vnd.cluetrust.cartomobile-config-pkg c11amz -# application/vnd.collection+json -# application/vnd.commerce-battelle -application/vnd.commonspace csp -application/vnd.contact.cmsg cdbcmsg -application/vnd.cosmocaller cmc -application/vnd.crick.clicker clkx -application/vnd.crick.clicker.keyboard clkk -application/vnd.crick.clicker.palette clkp -application/vnd.crick.clicker.template clkt -application/vnd.crick.clicker.wordbank clkw -application/vnd.criticaltools.wbs+xml wbs -application/vnd.ctc-posml pml -# application/vnd.ctct.ws+xml -# application/vnd.cups-pdf -# application/vnd.cups-postscript -application/vnd.cups-ppd ppd -# application/vnd.cups-raster -# application/vnd.cups-raw -# application/vnd.curl -application/vnd.curl.car car -application/vnd.curl.pcurl pcurl -# application/vnd.cybank -application/vnd.dart dart -application/vnd.data-vision.rdz rdz -application/vnd.dece.data uvf uvvf uvd uvvd -application/vnd.dece.ttml+xml uvt uvvt -application/vnd.dece.unspecified uvx uvvx -application/vnd.dece.zip uvz uvvz -application/vnd.denovo.fcselayout-link fe_launch -# application/vnd.dir-bi.plate-dl-nosuffix -application/vnd.dna dna -application/vnd.dolby.mlp mlp -# application/vnd.dolby.mobile.1 -# application/vnd.dolby.mobile.2 -application/vnd.dpgraph dpg -application/vnd.dreamfactory dfac -application/vnd.ds-keypoint kpxx -application/vnd.dvb.ait ait -# application/vnd.dvb.dvbj -# application/vnd.dvb.esgcontainer -# application/vnd.dvb.ipdcdftnotifaccess -# application/vnd.dvb.ipdcesgaccess -# application/vnd.dvb.ipdcesgaccess2 -# application/vnd.dvb.ipdcesgpdd -# application/vnd.dvb.ipdcroaming -# application/vnd.dvb.iptv.alfec-base -# application/vnd.dvb.iptv.alfec-enhancement -# application/vnd.dvb.notif-aggregate-root+xml -# application/vnd.dvb.notif-container+xml -# application/vnd.dvb.notif-generic+xml -# application/vnd.dvb.notif-ia-msglist+xml -# application/vnd.dvb.notif-ia-registration-request+xml -# application/vnd.dvb.notif-ia-registration-response+xml -# application/vnd.dvb.notif-init+xml -# application/vnd.dvb.pfr -application/vnd.dvb.service svc -# application/vnd.dxr -application/vnd.dynageo geo -# application/vnd.easykaraoke.cdgdownload -# application/vnd.ecdis-update -application/vnd.ecowin.chart mag -# application/vnd.ecowin.filerequest -# application/vnd.ecowin.fileupdate -# application/vnd.ecowin.series -# application/vnd.ecowin.seriesrequest -# application/vnd.ecowin.seriesupdate -# application/vnd.emclient.accessrequest+xml -application/vnd.enliven nml -# application/vnd.eprints.data+xml -application/vnd.epson.esf esf -application/vnd.epson.msf msf -application/vnd.epson.quickanime qam -application/vnd.epson.salt slt -application/vnd.epson.ssf ssf -# application/vnd.ericsson.quickcall -application/vnd.eszigno3+xml es3 et3 -# application/vnd.etsi.aoc+xml -# application/vnd.etsi.cug+xml -# application/vnd.etsi.iptvcommand+xml -# application/vnd.etsi.iptvdiscovery+xml -# application/vnd.etsi.iptvprofile+xml -# application/vnd.etsi.iptvsad-bc+xml -# application/vnd.etsi.iptvsad-cod+xml -# application/vnd.etsi.iptvsad-npvr+xml -# application/vnd.etsi.iptvservice+xml -# application/vnd.etsi.iptvsync+xml -# application/vnd.etsi.iptvueprofile+xml -# application/vnd.etsi.mcid+xml -# application/vnd.etsi.overload-control-policy-dataset+xml -# application/vnd.etsi.sci+xml -# application/vnd.etsi.simservs+xml -# application/vnd.etsi.tsl+xml -# application/vnd.etsi.tsl.der -# application/vnd.eudora.data -application/vnd.ezpix-album ez2 -application/vnd.ezpix-package ez3 -# application/vnd.f-secure.mobile -application/vnd.fdf fdf -application/vnd.fdsn.mseed mseed -application/vnd.fdsn.seed seed dataless -# application/vnd.ffsns -# application/vnd.fints -application/vnd.flographit gph -application/vnd.fluxtime.clip ftc -# application/vnd.font-fontforge-sfd -application/vnd.framemaker fm frame maker book -application/vnd.frogans.fnc fnc -application/vnd.frogans.ltf ltf -application/vnd.fsc.weblaunch fsc -application/vnd.fujitsu.oasys oas -application/vnd.fujitsu.oasys2 oa2 -application/vnd.fujitsu.oasys3 oa3 -application/vnd.fujitsu.oasysgp fg5 -application/vnd.fujitsu.oasysprs bh2 -# application/vnd.fujixerox.art-ex -# application/vnd.fujixerox.art4 -# application/vnd.fujixerox.hbpl -application/vnd.fujixerox.ddd ddd -application/vnd.fujixerox.docuworks xdw -application/vnd.fujixerox.docuworks.binder xbd -# application/vnd.fut-misnet -application/vnd.fuzzysheet fzs -application/vnd.genomatix.tuxedo txd -# application/vnd.geocube+xml -application/vnd.geogebra.file ggb -application/vnd.geogebra.tool ggt -application/vnd.geometry-explorer gex gre -application/vnd.geonext gxt -application/vnd.geoplan g2w -application/vnd.geospace g3w -# application/vnd.globalplatform.card-content-mgt -# application/vnd.globalplatform.card-content-mgt-response -application/vnd.gmx gmx -application/vnd.google-earth.kml+xml kml -application/vnd.google-earth.kmz kmz -application/vnd.grafeq gqf gqs -# application/vnd.gridmp -application/vnd.groove-account gac -application/vnd.groove-help ghf -application/vnd.groove-identity-message gim -application/vnd.groove-injector grv -application/vnd.groove-tool-message gtm -application/vnd.groove-tool-template tpl -application/vnd.groove-vcard vcg -# application/vnd.hal+json -application/vnd.hal+xml hal -application/vnd.handheld-entertainment+xml zmm -application/vnd.hbci hbci -# application/vnd.hcl-bireports -application/vnd.hhe.lesson-player les -application/vnd.hp-hpgl hpgl -application/vnd.hp-hpid hpid -application/vnd.hp-hps hps -application/vnd.hp-jlyt jlt -application/vnd.hp-pcl pcl -application/vnd.hp-pclxl pclxl -# application/vnd.httphone -application/vnd.hydrostatix.sof-data sfd-hdstx -# application/vnd.hzn-3d-crossword -# application/vnd.ibm.afplinedata -# application/vnd.ibm.electronic-media -application/vnd.ibm.minipay mpy -application/vnd.ibm.modcap afp listafp list3820 -application/vnd.ibm.rights-management irm -application/vnd.ibm.secure-container sc -application/vnd.iccprofile icc icm -application/vnd.igloader igl -application/vnd.immervision-ivp ivp -application/vnd.immervision-ivu ivu -# application/vnd.informedcontrol.rms+xml -# application/vnd.informix-visionary -# application/vnd.infotech.project -# application/vnd.infotech.project+xml -# application/vnd.innopath.wamp.notification -application/vnd.insors.igm igm -application/vnd.intercon.formnet xpw xpx -application/vnd.intergeo i2g -# application/vnd.intertrust.digibox -# application/vnd.intertrust.nncp -application/vnd.intu.qbo qbo -application/vnd.intu.qfx qfx -# application/vnd.iptc.g2.conceptitem+xml -# application/vnd.iptc.g2.knowledgeitem+xml -# application/vnd.iptc.g2.newsitem+xml -# application/vnd.iptc.g2.newsmessage+xml -# application/vnd.iptc.g2.packageitem+xml -# application/vnd.iptc.g2.planningitem+xml -application/vnd.ipunplugged.rcprofile rcprofile -application/vnd.irepository.package+xml irp -application/vnd.is-xpr xpr -application/vnd.isac.fcs fcs -application/vnd.jam jam -# application/vnd.japannet-directory-service -# application/vnd.japannet-jpnstore-wakeup -# application/vnd.japannet-payment-wakeup -# application/vnd.japannet-registration -# application/vnd.japannet-registration-wakeup -# application/vnd.japannet-setstore-wakeup -# application/vnd.japannet-verification -# application/vnd.japannet-verification-wakeup -application/vnd.jcp.javame.midlet-rms rms -application/vnd.jisp jisp -application/vnd.joost.joda-archive joda -application/vnd.kahootz ktz ktr -application/vnd.kde.karbon karbon -application/vnd.kde.kchart chrt -application/vnd.kde.kformula kfo -application/vnd.kde.kivio flw -application/vnd.kde.kontour kon -application/vnd.kde.kpresenter kpr kpt -application/vnd.kde.kspread ksp -application/vnd.kde.kword kwd kwt -application/vnd.kenameaapp htke -application/vnd.kidspiration kia -application/vnd.kinar kne knp -application/vnd.koan skp skd skt skm -application/vnd.kodak-descriptor sse -application/vnd.las.las+xml lasxml -# application/vnd.liberty-request+xml -application/vnd.llamagraphics.life-balance.desktop lbd -application/vnd.llamagraphics.life-balance.exchange+xml lbe -application/vnd.lotus-1-2-3 123 -application/vnd.lotus-approach apr -application/vnd.lotus-freelance pre -application/vnd.lotus-notes nsf -application/vnd.lotus-organizer org -application/vnd.lotus-screencam scm -application/vnd.lotus-wordpro lwp -application/vnd.macports.portpkg portpkg -# application/vnd.marlin.drm.actiontoken+xml -# application/vnd.marlin.drm.conftoken+xml -# application/vnd.marlin.drm.license+xml -# application/vnd.marlin.drm.mdcf -application/vnd.mcd mcd -application/vnd.medcalcdata mc1 -application/vnd.mediastation.cdkey cdkey -# application/vnd.meridian-slingshot -application/vnd.mfer mwf -application/vnd.mfmp mfm -application/vnd.micrografx.flo flo -application/vnd.micrografx.igx igx -application/vnd.mif mif -# application/vnd.minisoft-hp3000-save -# application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf daf -application/vnd.mobius.dis dis -application/vnd.mobius.mbk mbk -application/vnd.mobius.mqy mqy -application/vnd.mobius.msl msl -application/vnd.mobius.plc plc -application/vnd.mobius.txf txf -application/vnd.mophun.application mpn -application/vnd.mophun.certificate mpc -# application/vnd.motorola.flexsuite -# application/vnd.motorola.flexsuite.adsi -# application/vnd.motorola.flexsuite.fis -# application/vnd.motorola.flexsuite.gotap -# application/vnd.motorola.flexsuite.kmr -# application/vnd.motorola.flexsuite.ttc -# application/vnd.motorola.flexsuite.wem -# application/vnd.motorola.iprm -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry cil -# application/vnd.ms-asf -application/vnd.ms-cab-compressed cab -# application/vnd.ms-color.iccprofile -application/vnd.ms-excel xls xlm xla xlc xlt xlw -application/vnd.ms-excel.addin.macroenabled.12 xlam -application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb -application/vnd.ms-excel.sheet.macroenabled.12 xlsm -application/vnd.ms-excel.template.macroenabled.12 xltm -application/vnd.ms-fontobject eot -application/vnd.ms-htmlhelp chm -application/vnd.ms-ims ims -application/vnd.ms-lrm lrm -# application/vnd.ms-office.activex+xml -application/vnd.ms-officetheme thmx -# application/vnd.ms-opentype -# application/vnd.ms-package.obfuscated-opentype -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -# application/vnd.ms-playready.initiator+xml -application/vnd.ms-powerpoint ppt pps pot -application/vnd.ms-powerpoint.addin.macroenabled.12 ppam -application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm -application/vnd.ms-powerpoint.slide.macroenabled.12 sldm -application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm -application/vnd.ms-powerpoint.template.macroenabled.12 potm -# application/vnd.ms-printing.printticket+xml -application/vnd.ms-project mpp mpt -# application/vnd.ms-tnef -# application/vnd.ms-wmdrm.lic-chlg-req -# application/vnd.ms-wmdrm.lic-resp -# application/vnd.ms-wmdrm.meter-chlg-req -# application/vnd.ms-wmdrm.meter-resp -application/vnd.ms-word.document.macroenabled.12 docm -application/vnd.ms-word.template.macroenabled.12 dotm -application/vnd.ms-works wps wks wcm wdb -application/vnd.ms-wpl wpl -application/vnd.ms-xpsdocument xps -application/vnd.mseq mseq -# application/vnd.msign -# application/vnd.multiad.creator -# application/vnd.multiad.creator.cif -# application/vnd.music-niff -application/vnd.musician mus -application/vnd.muvee.style msty -application/vnd.mynfc taglet -# application/vnd.ncd.control -# application/vnd.ncd.reference -# application/vnd.nervana -# application/vnd.netfpx -application/vnd.neurolanguage.nlu nlu -application/vnd.nitf ntf nitf -application/vnd.noblenet-directory nnd -application/vnd.noblenet-sealer nns -application/vnd.noblenet-web nnw -# application/vnd.nokia.catalogs -# application/vnd.nokia.conml+wbxml -# application/vnd.nokia.conml+xml -# application/vnd.nokia.isds-radio-presets -# application/vnd.nokia.iptv.config+xml -# application/vnd.nokia.landmark+wbxml -# application/vnd.nokia.landmark+xml -# application/vnd.nokia.landmarkcollection+xml -# application/vnd.nokia.n-gage.ac+xml -application/vnd.nokia.n-gage.data ngdat -application/vnd.nokia.n-gage.symbian.install n-gage -# application/vnd.nokia.ncd -# application/vnd.nokia.pcd+wbxml -# application/vnd.nokia.pcd+xml -application/vnd.nokia.radio-preset rpst -application/vnd.nokia.radio-presets rpss -application/vnd.novadigm.edm edm -application/vnd.novadigm.edx edx -application/vnd.novadigm.ext ext -# application/vnd.ntt-local.file-transfer -# application/vnd.ntt-local.sip-ta_remote -# application/vnd.ntt-local.sip-ta_tcp_stream -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.chart-template otc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.formula-template odft -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.image-template oti -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -# application/vnd.obn -# application/vnd.oftn.l10n+json -# application/vnd.oipf.contentaccessdownload+xml -# application/vnd.oipf.contentaccessstreaming+xml -# application/vnd.oipf.cspg-hexbinary -# application/vnd.oipf.dae.svg+xml -# application/vnd.oipf.dae.xhtml+xml -# application/vnd.oipf.mippvcontrolmessage+xml -# application/vnd.oipf.pae.gem -# application/vnd.oipf.spdiscovery+xml -# application/vnd.oipf.spdlist+xml -# application/vnd.oipf.ueprofile+xml -# application/vnd.oipf.userprofile+xml -application/vnd.olpc-sugar xo -# application/vnd.oma-scws-config -# application/vnd.oma-scws-http-request -# application/vnd.oma-scws-http-response -# application/vnd.oma.bcast.associated-procedure-parameter+xml -# application/vnd.oma.bcast.drm-trigger+xml -# application/vnd.oma.bcast.imd+xml -# application/vnd.oma.bcast.ltkm -# application/vnd.oma.bcast.notification+xml -# application/vnd.oma.bcast.provisioningtrigger -# application/vnd.oma.bcast.sgboot -# application/vnd.oma.bcast.sgdd+xml -# application/vnd.oma.bcast.sgdu -# application/vnd.oma.bcast.simple-symbol-container -# application/vnd.oma.bcast.smartcard-trigger+xml -# application/vnd.oma.bcast.sprov+xml -# application/vnd.oma.bcast.stkm -# application/vnd.oma.cab-address-book+xml -# application/vnd.oma.cab-feature-handler+xml -# application/vnd.oma.cab-pcc+xml -# application/vnd.oma.cab-user-prefs+xml -# application/vnd.oma.dcd -# application/vnd.oma.dcdc -application/vnd.oma.dd2+xml dd2 -# application/vnd.oma.drm.risd+xml -# application/vnd.oma.group-usage-list+xml -# application/vnd.oma.pal+xml -# application/vnd.oma.poc.detailed-progress-report+xml -# application/vnd.oma.poc.final-report+xml -# application/vnd.oma.poc.groups+xml -# application/vnd.oma.poc.invocation-descriptor+xml -# application/vnd.oma.poc.optimized-progress-report+xml -# application/vnd.oma.push -# application/vnd.oma.scidm.messages+xml -# application/vnd.oma.xcap-directory+xml -# application/vnd.omads-email+xml -# application/vnd.omads-file+xml -# application/vnd.omads-folder+xml -# application/vnd.omaloc-supl-init -application/vnd.openofficeorg.extension oxt -# application/vnd.openxmlformats-officedocument.custom-properties+xml -# application/vnd.openxmlformats-officedocument.customxmlproperties+xml -# application/vnd.openxmlformats-officedocument.drawing+xml -# application/vnd.openxmlformats-officedocument.drawingml.chart+xml -# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml -# application/vnd.openxmlformats-officedocument.extended-properties+xml -# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml -# application/vnd.openxmlformats-officedocument.presentationml.comments+xml -# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml -application/vnd.openxmlformats-officedocument.presentationml.presentation pptx -# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml -application/vnd.openxmlformats-officedocument.presentationml.slide sldx -# application/vnd.openxmlformats-officedocument.presentationml.slide+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml -application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx -# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml -# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml -# application/vnd.openxmlformats-officedocument.presentationml.tags+xml -application/vnd.openxmlformats-officedocument.presentationml.template potx -# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx -# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml -# application/vnd.openxmlformats-officedocument.theme+xml -# application/vnd.openxmlformats-officedocument.themeoverride+xml -# application/vnd.openxmlformats-officedocument.vmldrawing -# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.document docx -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx -# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml -# application/vnd.openxmlformats-package.core-properties+xml -# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml -# application/vnd.openxmlformats-package.relationships+xml -# application/vnd.quobject-quoxdocument -# application/vnd.osa.netdeploy -application/vnd.osgeo.mapguide.package mgp -# application/vnd.osgi.bundle -application/vnd.osgi.dp dp -application/vnd.osgi.subsystem esa -# application/vnd.otps.ct-kip+xml -application/vnd.palm pdb pqa oprc -# application/vnd.paos.xml -application/vnd.pawaafile paw -application/vnd.pg.format str -application/vnd.pg.osasli ei6 -# application/vnd.piaccess.application-licence -application/vnd.picsel efif -application/vnd.pmi.widget wg -# application/vnd.poc.group-advertisement+xml -application/vnd.pocketlearn plf -application/vnd.powerbuilder6 pbd -# application/vnd.powerbuilder6-s -# application/vnd.powerbuilder7 -# application/vnd.powerbuilder7-s -# application/vnd.powerbuilder75 -# application/vnd.powerbuilder75-s -# application/vnd.preminet -application/vnd.previewsystems.box box -application/vnd.proteus.magazine mgz -application/vnd.publishare-delta-tree qps -application/vnd.pvi.ptid1 ptid -# application/vnd.pwg-multiplexed -# application/vnd.pwg-xhtml-print+xml -# application/vnd.qualcomm.brew-app-res -application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb -# application/vnd.radisys.moml+xml -# application/vnd.radisys.msml+xml -# application/vnd.radisys.msml-audit+xml -# application/vnd.radisys.msml-audit-conf+xml -# application/vnd.radisys.msml-audit-conn+xml -# application/vnd.radisys.msml-audit-dialog+xml -# application/vnd.radisys.msml-audit-stream+xml -# application/vnd.radisys.msml-conf+xml -# application/vnd.radisys.msml-dialog+xml -# application/vnd.radisys.msml-dialog-base+xml -# application/vnd.radisys.msml-dialog-fax-detect+xml -# application/vnd.radisys.msml-dialog-fax-sendrecv+xml -# application/vnd.radisys.msml-dialog-group+xml -# application/vnd.radisys.msml-dialog-speech+xml -# application/vnd.radisys.msml-dialog-transform+xml -# application/vnd.rainstor.data -# application/vnd.rapid -application/vnd.realvnc.bed bed -application/vnd.recordare.musicxml mxl -application/vnd.recordare.musicxml+xml musicxml -# application/vnd.renlearn.rlprint -application/vnd.rig.cryptonote cryptonote -application/vnd.rim.cod cod -application/vnd.rn-realmedia rm -application/vnd.rn-realmedia-vbr rmvb -application/vnd.route66.link66+xml link66 -# application/vnd.rs-274x -# application/vnd.ruckus.download -# application/vnd.s3sms -application/vnd.sailingtracker.track st -# application/vnd.sbm.cid -# application/vnd.sbm.mid2 -# application/vnd.scribus -# application/vnd.sealed.3df -# application/vnd.sealed.csf -# application/vnd.sealed.doc -# application/vnd.sealed.eml -# application/vnd.sealed.mht -# application/vnd.sealed.net -# application/vnd.sealed.ppt -# application/vnd.sealed.tiff -# application/vnd.sealed.xls -# application/vnd.sealedmedia.softseal.html -# application/vnd.sealedmedia.softseal.pdf -application/vnd.seemail see -application/vnd.sema sema -application/vnd.semd semd -application/vnd.semf semf -application/vnd.shana.informed.formdata ifm -application/vnd.shana.informed.formtemplate itp -application/vnd.shana.informed.interchange iif -application/vnd.shana.informed.package ipk -application/vnd.simtech-mindmapper twd twds -application/vnd.smaf mmf -# application/vnd.smart.notebook -application/vnd.smart.teacher teacher -# application/vnd.software602.filler.form+xml -# application/vnd.software602.filler.form-xml-zip -application/vnd.solent.sdkm+xml sdkm sdkd -application/vnd.spotfire.dxp dxp -application/vnd.spotfire.sfs sfs -# application/vnd.sss-cod -# application/vnd.sss-dtf -# application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.stepmania.package smzip -application/vnd.stepmania.stepchart sm -# application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -# application/vnd.sun.wadl+xml -application/vnd.sus-calendar sus susp -application/vnd.svd svd -# application/vnd.swiftview-ics -application/vnd.symbian.install sis sisx -application/vnd.syncml+xml xsm -application/vnd.syncml.dm+wbxml bdm -application/vnd.syncml.dm+xml xdm -# application/vnd.syncml.dm.notification -# application/vnd.syncml.ds.notification -application/vnd.tao.intent-module-archive tao -application/vnd.tcpdump.pcap pcap cap dmp -application/vnd.tmobile-livetv tmo -application/vnd.trid.tpt tpt -application/vnd.triscape.mxs mxs -application/vnd.trueapp tra -# application/vnd.truedoc -# application/vnd.ubisoft.webplayer -application/vnd.ufdl ufd ufdl -application/vnd.uiq.theme utz -application/vnd.umajin umj -application/vnd.unity unityweb -application/vnd.uoml+xml uoml -# application/vnd.uplanet.alert -# application/vnd.uplanet.alert-wbxml -# application/vnd.uplanet.bearer-choice -# application/vnd.uplanet.bearer-choice-wbxml -# application/vnd.uplanet.cacheop -# application/vnd.uplanet.cacheop-wbxml -# application/vnd.uplanet.channel -# application/vnd.uplanet.channel-wbxml -# application/vnd.uplanet.list -# application/vnd.uplanet.list-wbxml -# application/vnd.uplanet.listcmd -# application/vnd.uplanet.listcmd-wbxml -# application/vnd.uplanet.signal -application/vnd.vcx vcx -# application/vnd.vd-study -# application/vnd.vectorworks -# application/vnd.verimatrix.vcas -# application/vnd.vidsoft.vidconference -application/vnd.visio vsd vst vss vsw -application/vnd.visionary vis -# application/vnd.vividence.scriptfile -application/vnd.vsf vsf -# application/vnd.wap.sic -# application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo wtb -# application/vnd.wfa.wsc -# application/vnd.wmc -# application/vnd.wmf.bootstrap -# application/vnd.wolfram.mathematica -# application/vnd.wolfram.mathematica.package -application/vnd.wolfram.player nbp -application/vnd.wordperfect wpd -application/vnd.wqd wqd -# application/vnd.wrq-hp3000-labelled -application/vnd.wt.stf stf -# application/vnd.wv.csp+wbxml -# application/vnd.wv.csp+xml -# application/vnd.wv.ssp+xml -application/vnd.xara xar -application/vnd.xfdl xfdl -# application/vnd.xfdl.webform -# application/vnd.xmi+xml -# application/vnd.xmpie.cpkg -# application/vnd.xmpie.dpkg -# application/vnd.xmpie.plan -# application/vnd.xmpie.ppkg -# application/vnd.xmpie.xlim -application/vnd.yamaha.hv-dic hvd -application/vnd.yamaha.hv-script hvs -application/vnd.yamaha.hv-voice hvp -application/vnd.yamaha.openscoreformat osf -application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg -# application/vnd.yamaha.remote-setup -application/vnd.yamaha.smaf-audio saf -application/vnd.yamaha.smaf-phrase spf -# application/vnd.yamaha.through-ngn -# application/vnd.yamaha.tunnel-udpencap -application/vnd.yellowriver-custom-menu cmp -application/vnd.zul zir zirz -application/vnd.zzazz.deck+xml zaz -application/voicexml+xml vxml -# application/vq-rtcpxr -# application/watcherinfo+xml -# application/whoispp-query -# application/whoispp-response -application/widget wgt -application/winhlp hlp -# application/wita -# application/wordperfect5.1 -application/wsdl+xml wsdl -application/wspolicy+xml wspolicy -application/x-7z-compressed 7z -application/x-abiword abw -application/x-ace-compressed ace -# application/x-amf -application/x-apple-diskimage dmg -application/x-authorware-bin aab x32 u32 vox -application/x-authorware-map aam -application/x-authorware-seg aas -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-blorb blb blorb -application/x-bzip bz -application/x-bzip2 bz2 boz -application/x-cbr cbr cba cbt cbz cb7 -application/x-cdlink vcd -application/x-cfs-compressed cfs -application/x-chat chat -application/x-chess-pgn pgn -application/x-conference nsc -# application/x-compress -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-dgc-compressed dgc -application/x-director dir dcr dxr cst cct cxt w3d fgd swa -application/x-doom wad -application/x-dtbncx+xml ncx -application/x-dtbook+xml dtb -application/x-dtbresource+xml res -application/x-dvi dvi -application/x-envoy evy -application/x-eva eva -application/x-font-bdf bdf -# application/x-font-dos -# application/x-font-framemaker -application/x-font-ghostscript gsf -# application/x-font-libgrx -application/x-font-linux-psf psf -application/x-font-otf otf -application/x-font-pcf pcf -application/x-font-snf snf -# application/x-font-speedo -# application/x-font-sunos-news -application/x-font-ttf ttf ttc -application/x-font-type1 pfa pfb pfm afm -application/font-woff woff -# application/x-font-vfont -application/x-freearc arc -application/x-futuresplash spl -application/x-gca-compressed gca -application/x-glulx ulx -application/x-gnumeric gnumeric -application/x-gramps-xml gramps -application/x-gtar gtar -# application/x-gzip -application/x-hdf hdf -application/x-install-instructions install -application/x-iso9660-image iso -application/x-java-jnlp-file jnlp -application/x-latex latex -application/x-lzh-compressed lzh lha -application/x-mie mie -application/x-mobipocket-ebook prc mobi -application/x-ms-application application -application/x-ms-shortcut lnk -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-ms-xbap xbap -application/x-msaccess mdb -application/x-msbinder obd -application/x-mscardfile crd -application/x-msclip clp -application/x-msdownload exe dll com bat msi -application/x-msmediaview mvb m13 m14 -application/x-msmetafile wmf wmz emf emz -application/x-msmoney mny -application/x-mspublisher pub -application/x-msschedule scd -application/x-msterminal trm -application/x-mswrite wri -application/x-netcdf nc cdf -application/x-nzb nzb -application/x-pkcs12 p12 pfx -application/x-pkcs7-certificates p7b spc -application/x-pkcs7-certreqresp p7r -application/x-rar-compressed rar -application/x-research-info-systems ris -application/x-sh sh -application/x-shar shar -application/x-shockwave-flash swf -application/x-silverlight-app xap -application/x-sql sql -application/x-stuffit sit -application/x-stuffitx sitx -application/x-subrip srt -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-t3vm-image t3 -application/x-tads gam -application/x-tar tar -application/x-tcl tcl -application/x-tex tex -application/x-tex-tfm tfm -application/x-texinfo texinfo texi -application/x-tgif obj -application/x-ustar ustar -application/x-wais-source src -application/x-x509-ca-cert der crt -application/x-xfig fig -application/x-xliff+xml xlf -application/x-xpinstall xpi -application/x-xz xz -application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 -# application/x400-bp -application/xaml+xml xaml -# application/xcap-att+xml -# application/xcap-caps+xml -application/xcap-diff+xml xdf -# application/xcap-el+xml -# application/xcap-error+xml -# application/xcap-ns+xml -# application/xcon-conference-info-diff+xml -# application/xcon-conference-info+xml -application/xenc+xml xenc -application/xhtml+xml xhtml xht -# application/xhtml-voice+xml -application/xml xml xsl -application/xml-dtd dtd -# application/xml-external-parsed-entity -# application/xmpp+xml -application/xop+xml xop -application/xproc+xml xpl -application/xslt+xml xslt -application/xspf+xml xspf -application/xv+xml mxml xhvml xvml xvm -application/yang yang -application/yin+xml yin -application/zip zip -# audio/1d-interleaved-parityfec -# audio/32kadpcm -# audio/3gpp -# audio/3gpp2 -# audio/ac3 -audio/adpcm adp -# audio/amr -# audio/amr-wb -# audio/amr-wb+ -# audio/asc -# audio/atrac-advanced-lossless -# audio/atrac-x -# audio/atrac3 -audio/basic au snd -# audio/bv16 -# audio/bv32 -# audio/clearmode -# audio/cn -# audio/dat12 -# audio/dls -# audio/dsr-es201108 -# audio/dsr-es202050 -# audio/dsr-es202211 -# audio/dsr-es202212 -# audio/dv -# audio/dvi4 -# audio/eac3 -# audio/evrc -# audio/evrc-qcp -# audio/evrc0 -# audio/evrc1 -# audio/evrcb -# audio/evrcb0 -# audio/evrcb1 -# audio/evrcwb -# audio/evrcwb0 -# audio/evrcwb1 -# audio/example -# audio/fwdred -# audio/g719 -# audio/g722 -# audio/g7221 -# audio/g723 -# audio/g726-16 -# audio/g726-24 -# audio/g726-32 -# audio/g726-40 -# audio/g728 -# audio/g729 -# audio/g7291 -# audio/g729d -# audio/g729e -# audio/gsm -# audio/gsm-efr -# audio/gsm-hr-08 -# audio/ilbc -# audio/ip-mr_v2.5 -# audio/isac -# audio/l16 -# audio/l20 -# audio/l24 -# audio/l8 -# audio/lpc -audio/midi mid midi kar rmi -# audio/mobile-xmf -audio/mp4 mp4a -# audio/mp4a-latm -# audio/mpa -# audio/mpa-robust -audio/mpeg mpga mp2 mp2a mp3 m2a m3a -# audio/mpeg4-generic -# audio/musepack -audio/ogg oga ogg spx -# audio/opus -# audio/parityfec -# audio/pcma -# audio/pcma-wb -# audio/pcmu-wb -# audio/pcmu -# audio/prs.sid -# audio/qcelp -# audio/red -# audio/rtp-enc-aescm128 -# audio/rtp-midi -# audio/rtx -audio/s3m s3m -audio/silk sil -# audio/smv -# audio/smv0 -# audio/smv-qcp -# audio/sp-midi -# audio/speex -# audio/t140c -# audio/t38 -# audio/telephone-event -# audio/tone -# audio/uemclip -# audio/ulpfec -# audio/vdvi -# audio/vmr-wb -# audio/vnd.3gpp.iufp -# audio/vnd.4sb -# audio/vnd.audiokoz -# audio/vnd.celp -# audio/vnd.cisco.nse -# audio/vnd.cmles.radio-events -# audio/vnd.cns.anp1 -# audio/vnd.cns.inf1 -audio/vnd.dece.audio uva uvva -audio/vnd.digital-winds eol -# audio/vnd.dlna.adts -# audio/vnd.dolby.heaac.1 -# audio/vnd.dolby.heaac.2 -# audio/vnd.dolby.mlp -# audio/vnd.dolby.mps -# audio/vnd.dolby.pl2 -# audio/vnd.dolby.pl2x -# audio/vnd.dolby.pl2z -# audio/vnd.dolby.pulse.1 -audio/vnd.dra dra -audio/vnd.dts dts -audio/vnd.dts.hd dtshd -# audio/vnd.dvb.file -# audio/vnd.everad.plj -# audio/vnd.hns.audio -audio/vnd.lucent.voice lvp -audio/vnd.ms-playready.media.pya pya -# audio/vnd.nokia.mobile-xmf -# audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 ecelp4800 -audio/vnd.nuera.ecelp7470 ecelp7470 -audio/vnd.nuera.ecelp9600 ecelp9600 -# audio/vnd.octel.sbc -# audio/vnd.qcelp -# audio/vnd.rhetorex.32kadpcm -audio/vnd.rip rip -# audio/vnd.sealedmedia.softseal.mpeg -# audio/vnd.vmx.cvsd -# audio/vorbis -# audio/vorbis-config -audio/webm weba -audio/x-aac aac -audio/x-aiff aif aiff aifc -audio/x-caf caf -audio/x-flac flac -audio/x-matroska mka -audio/x-mpegurl m3u -audio/x-ms-wax wax -audio/x-ms-wma wma -audio/x-pn-realaudio ram ra -audio/x-pn-realaudio-plugin rmp -# audio/x-tta -audio/x-wav wav -audio/xm xm -chemical/x-cdx cdx -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-csml csml -# chemical/x-pdb -chemical/x-xyz xyz -image/bmp bmp -image/cgm cgm -# image/example -# image/fits -image/g3fax g3 -image/gif gif -image/ief ief -# image/jp2 -image/jpeg jpeg jpg jpe -# image/jpm -# image/jpx -image/ktx ktx -# image/naplps -image/png png -image/prs.btif btif -# image/prs.pti -image/sgi sgi -image/svg+xml svg svgz -# image/t38 -image/tiff tiff tif -# image/tiff-fx -image/vnd.adobe.photoshop psd -# image/vnd.cns.inf2 -image/vnd.dece.graphic uvi uvvi uvg uvvg -image/vnd.dvb.subtitle sub -image/vnd.djvu djvu djv -image/vnd.dwg dwg -image/vnd.dxf dxf -image/vnd.fastbidsheet fbs -image/vnd.fpx fpx -image/vnd.fst fst -image/vnd.fujixerox.edmics-mmr mmr -image/vnd.fujixerox.edmics-rlc rlc -# image/vnd.globalgraphics.pgb -# image/vnd.microsoft.icon -# image/vnd.mix -image/vnd.ms-modi mdi -image/vnd.ms-photo wdp -image/vnd.net-fpx npx -# image/vnd.radiance -# image/vnd.sealed.png -# image/vnd.sealedmedia.softseal.gif -# image/vnd.sealedmedia.softseal.jpg -# image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff xif -image/webp webp -image/x-3ds 3ds -image/x-cmu-raster ras -image/x-cmx cmx -image/x-freehand fh fhc fh4 fh5 fh7 -image/x-icon ico -image/x-mrsid-image sid -image/x-pcx pcx -image/x-pict pic pct -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-tga tga -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd -# message/cpim -# message/delivery-status -# message/disposition-notification -# message/example -# message/external-body -# message/feedback-report -# message/global -# message/global-delivery-status -# message/global-disposition-notification -# message/global-headers -# message/http -# message/imdn+xml -# message/news -# message/partial -message/rfc822 eml mime -# message/s-http -# message/sip -# message/sipfrag -# message/tracking-status -# message/vnd.si.simp -# model/example -model/iges igs iges -model/mesh msh mesh silo -model/vnd.collada+xml dae -model/vnd.dwf dwf -# model/vnd.flatland.3dml -model/vnd.gdl gdl -# model/vnd.gs-gdl -# model/vnd.gs.gdl -model/vnd.gtw gtw -# model/vnd.moml+xml -model/vnd.mts mts -# model/vnd.parasolid.transmit.binary -# model/vnd.parasolid.transmit.text -model/vnd.vtu vtu -model/vrml wrl vrml -model/x3d+binary x3db x3dbz -model/x3d+vrml x3dv x3dvz -model/x3d+xml x3d x3dz -# multipart/alternative -# multipart/appledouble -# multipart/byteranges -# multipart/digest -# multipart/encrypted -# multipart/example -# multipart/form-data -# multipart/header-set -# multipart/mixed -# multipart/parallel -# multipart/related -# multipart/report -# multipart/signed -# multipart/voice-message -# text/1d-interleaved-parityfec -text/cache-manifest appcache -text/calendar ics ifb -text/css css -text/csv csv -# text/directory -# text/dns -# text/ecmascript -# text/enriched -# text/example -# text/fwdred -text/html html htm -# text/javascript -text/n3 n3 -# text/parityfec -text/plain txt text conf def list log in -# text/prs.fallenstein.rst -text/prs.lines.tag dsc -# text/vnd.radisys.msml-basic-layout -# text/red -# text/rfc822-headers -text/richtext rtx -# text/rtf -# text/rtp-enc-aescm128 -# text/rtx -text/sgml sgml sgm -# text/t140 -text/tab-separated-values tsv -text/troff t tr roff man me ms -text/turtle ttl -# text/ulpfec -text/uri-list uri uris urls -text/vcard vcard -# text/vnd.abc -text/vnd.curl curl -text/vnd.curl.dcurl dcurl -text/vnd.curl.scurl scurl -text/vnd.curl.mcurl mcurl -# text/vnd.dmclientscript -text/vnd.dvb.subtitle sub -# text/vnd.esmertec.theme-descriptor -text/vnd.fly fly -text/vnd.fmi.flexstor flx -text/vnd.graphviz gv -text/vnd.in3d.3dml 3dml -text/vnd.in3d.spot spot -# text/vnd.iptc.newsml -# text/vnd.iptc.nitf -# text/vnd.latex-z -# text/vnd.motorola.reflex -# text/vnd.ms-mediapackage -# text/vnd.net2phone.commcenter.command -# text/vnd.si.uricatalogue -text/vnd.sun.j2me.app-descriptor jad -# text/vnd.trolltech.linguist -# text/vnd.wap.si -# text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-asm s asm -text/x-c c cc cxx cpp h hh dic -text/x-fortran f for f77 f90 -text/x-java-source java -text/x-opml opml -text/x-pascal p pas -text/x-nfo nfo -text/x-setext etx -text/x-sfv sfv -text/x-uuencode uu -text/x-vcalendar vcs -text/x-vcard vcf -# text/xml -# text/xml-external-parsed-entity -# video/1d-interleaved-parityfec -video/3gpp 3gp -# video/3gpp-tt -video/3gpp2 3g2 -# video/bmpeg -# video/bt656 -# video/celb -# video/dv -# video/example -video/h261 h261 -video/h263 h263 -# video/h263-1998 -# video/h263-2000 -video/h264 h264 -# video/h264-rcdo -# video/h264-svc -video/jpeg jpgv -# video/jpeg2000 -video/jpm jpm jpgm -video/mj2 mj2 mjp2 -# video/mp1s -# video/mp2p -# video/mp2t -video/mp4 mp4 mp4v mpg4 -# video/mp4v-es -video/mpeg mpeg mpg mpe m1v m2v -# video/mpeg4-generic -# video/mpv -# video/nv -video/ogg ogv -# video/parityfec -# video/pointer -video/quicktime qt mov -# video/raw -# video/rtp-enc-aescm128 -# video/rtx -# video/smpte292m -# video/ulpfec -# video/vc1 -# video/vnd.cctv -video/vnd.dece.hd uvh uvvh -video/vnd.dece.mobile uvm uvvm -# video/vnd.dece.mp4 -video/vnd.dece.pd uvp uvvp -video/vnd.dece.sd uvs uvvs -video/vnd.dece.video uvv uvvv -# video/vnd.directv.mpeg -# video/vnd.directv.mpeg-tts -# video/vnd.dlna.mpeg-tts -video/vnd.dvb.file dvb -video/vnd.fvt fvt -# video/vnd.hns.video -# video/vnd.iptvforum.1dparityfec-1010 -# video/vnd.iptvforum.1dparityfec-2005 -# video/vnd.iptvforum.2dparityfec-1010 -# video/vnd.iptvforum.2dparityfec-2005 -# video/vnd.iptvforum.ttsavc -# video/vnd.iptvforum.ttsmpeg2 -# video/vnd.motorola.video -# video/vnd.motorola.videop -video/vnd.mpegurl mxu m4u -video/vnd.ms-playready.media.pyv pyv -# video/vnd.nokia.interleaved-multimedia -# video/vnd.nokia.videovoip -# video/vnd.objectvideo -# video/vnd.sealed.mpeg1 -# video/vnd.sealed.mpeg4 -# video/vnd.sealed.swf -# video/vnd.sealedmedia.softseal.mov -video/vnd.uvvu.mp4 uvu uvvu -video/vnd.vivo viv -video/webm webm -video/x-f4v f4v -video/x-fli fli -video/x-flv flv -video/x-m4v m4v -video/x-matroska mkv mk3d mks -video/x-mng mng -video/x-ms-asf asf asx -video/x-ms-vob vob -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie -video/x-smv smv -x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/node.types b/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/node.types deleted file mode 100644 index 55b2cf7..0000000 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/types/node.types +++ /dev/null @@ -1,77 +0,0 @@ -# What: WebVTT -# Why: To allow formats intended for marking up external text track resources. -# http://dev.w3.org/html5/webvtt/ -# Added by: niftylettuce -text/vtt vtt - -# What: Google Chrome Extension -# Why: To allow apps to (work) be served with the right content type header. -# http://codereview.chromium.org/2830017 -# Added by: niftylettuce -application/x-chrome-extension crx - -# What: HTC support -# Why: To properly render .htc files such as CSS3PIE -# Added by: niftylettuce -text/x-component htc - -# What: HTML5 application cache manifes ('.manifest' extension) -# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps -# per https://developer.mozilla.org/en/offline_resources_in_firefox -# Added by: louisremi -text/cache-manifest manifest - -# What: node binary buffer format -# Why: semi-standard extension w/in the node community -# Added by: tootallnate -application/octet-stream buffer - -# What: The "protected" MP-4 formats used by iTunes. -# Why: Required for streaming music to browsers (?) -# Added by: broofa -application/mp4 m4p -audio/mp4 m4a - -# What: Video format, Part of RFC1890 -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -video/MP2T ts - -# What: EventSource mime type -# Why: mime type of Server-Sent Events stream -# http://www.w3.org/TR/eventsource/#text-event-stream -# Added by: francois2metz -text/event-stream event-stream - -# What: Mozilla App manifest mime type -# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests -# Added by: ednapiranha -application/x-web-app-manifest+json webapp - -# What: Lua file types -# Why: Googling around shows de-facto consensus on these -# Added by: creationix (Issue #45) -text/x-lua lua -application/x-lua-bytecode luac - -# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax -# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown -# Added by: avoidwork -text/x-markdown markdown md mkd - -# What: ini files -# Why: because they're just text files -# Added by: Matthew Kastor -text/plain ini - -# What: DASH Adaptive Streaming manifest -# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video -# Added by: eelcocramer -application/dash+xml mdp - -# What: OpenType font files - http://www.microsoft.com/typography/otspec/ -# Why: Browsers usually ignore the font MIME types and sniff the content, -# but Chrome, shows a warning if OpenType fonts aren't served with -# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. -# Added by: alrra -font/opentype otf diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/.npmignore b/node_modules/express/node_modules/type-is/node_modules/mime-types/.npmignore deleted file mode 100644 index 919d51b..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/.npmignore +++ /dev/null @@ -1,14 +0,0 @@ -test -build.js - -# OS generated files # -###################### -.DS_Store* -# Icon? -ehthumbs.db -Thumbs.db - -# Node.js # -########### -node_modules -npm-debug.log diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/.travis.yml b/node_modules/express/node_modules/type-is/node_modules/mime-types/.travis.yml deleted file mode 100644 index 73c85c6..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.11" -matrix: - allow_failures: - - node_js: "0.11" - fast_finish: true -before_install: - # remove build script deps before install - - node -pe 'f="./package.json";p=require(f);d=p.devDependencies;for(k in d){if("co"===k.substr(0,2))delete d[k]}require("fs").writeFileSync(f,JSON.stringify(p,null,2))' diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/Makefile b/node_modules/express/node_modules/type-is/node_modules/mime-types/Makefile deleted file mode 100644 index ceaf011..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/Makefile +++ /dev/null @@ -1,9 +0,0 @@ - -build: - node --harmony-generators build.js - -test: - node test/mime.js - mocha --require should --reporter spec test/test.js - -.PHONY: build test diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md b/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md deleted file mode 100644 index 8e21ee1..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# mime-types -[![NPM version](https://badge.fury.io/js/mime-types.svg)](https://badge.fury.io/js/mime-types) [![Build Status](https://travis-ci.org/expressjs/mime-types.svg?branch=master)](https://travis-ci.org/expressjs/mime-types) - -The ultimate javascript content-type utility. - -### Install - -```sh -$ npm install mime-types -``` - -#### Similar to [node-mime](https://github.com/broofa/node-mime), except: - -- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. -- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. -- Additional mime types are added such as jade and stylus. Feel free to add more! -- Browser support via Browserify and Component by converting lists to JSON files. - -Otherwise, the API is compatible. - -### Adding Types - -If you'd like to add additional types, -simply create a PR adding the type to `custom.json` and -a reference link to the [sources](SOURCES.md). - -Do __NOT__ edit `mime.json` or `node.json`. -Those are pulled using `build.js`. -You should only touch `custom.json`. - -## API - -```js -var mime = require('mime-types') -``` - -All functions return `false` if input is invalid or not found. - -### mime.lookup(path) - -Lookup the content-type associated with a file. - -```js -mime.lookup('json') // 'application/json' -mime.lookup('.md') // 'text/x-markdown' -mime.lookup('file.html') // 'text/html' -mime.lookup('folder/file.js') // 'application/javascript' - -mime.lookup('cats') // false -``` - -### mime.contentType(type) - -Create a full content-type header given a content-type or extension. - -```js -mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' -mime.contentType('file.json') // 'application/json; charset=utf-8' -``` - -### mime.extension(type) - -Get the default extension for a content-type. - -```js -mime.extension('application/octet-stream') // 'bin' -``` - -### mime.charset(type) - -Lookup the implied default charset of a content-type. - -```js -mime.charset('text/x-markdown') // 'UTF-8' -``` - -### mime.types[extension] = type - -A map of content-types by extension. - -### mime.extensions[type] = [extensions] - -A map of extensions by content-type. - -### mime.define(types) - -Globally add definitions. -`types` must be an object of the form: - -```js -{ - "": [extensions...], - "": [extensions...] -} -``` - -See the `.json` files in `lib/` for examples. - -## License - -[MIT](LICENSE) diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/SOURCES.md b/node_modules/express/node_modules/type-is/node_modules/mime-types/SOURCES.md deleted file mode 100644 index 1d65012..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/SOURCES.md +++ /dev/null @@ -1,17 +0,0 @@ - -### Sources for custom types - -This is a list of sources for any custom mime types. -When adding custom mime types, please link to where you found the mime type, -even if it's from an unofficial source. - -- `text/coffeescript` - http://coffeescript.org/#scripts -- `text/x-handlebars-template` - https://handlebarsjs.com/#getting-started -- `text/x-sass` & `text/x-scss` - https://github.com/janlelis/rubybuntu-mime/blob/master/sass.xml -- `text.jsx` - http://facebook.github.io/react/docs/getting-started.html [[2]](https://github.com/facebook/react/blob/f230e0a03154e6f8a616e0da1fb3d97ffa1a6472/vendor/browser-transforms.js#L210) - -[Sources for node.json types](https://github.com/broofa/node-mime/blob/master/types/node.types) - -### Notes on weird types - -- `font/opentype` - This type is technically invalid according to the spec. No valid types begin with `font/`. No-one uses the official type of `application/vnd.ms-opentype` as the community standardized `application/x-font-otf`. However, chrome logs nonsense warnings unless opentype fonts are served with `font/opentype`. [[1]](http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts) diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/component.json b/node_modules/express/node_modules/type-is/node_modules/mime-types/component.json deleted file mode 100644 index fa67a6d..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/component.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "mime-types", - "description": "The ultimate javascript content-type utility.", - "version": "0.1.0", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com", - "twitter": "https://twitter.com/jongleberry" - }, - "repository": "expressjs/mime-types", - "license": "MIT", - "main": "lib/index.js", - "scripts": ["lib/index.js"], - "json": ["mime.json", "node.json", "custom.json"] -} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/custom.json b/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/custom.json deleted file mode 100644 index 6137da3..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/custom.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "text/jade": [ - "jade" - ], - "text/stylus": [ - "stylus", - "styl" - ], - "text/less": [ - "less" - ], - "text/x-sass": [ - "sass" - ], - "text/x-scss": [ - "scss" - ], - "text/coffeescript": [ - "coffee" - ], - "text/x-handlebars-template": [ - "hbs" - ], - "text/jsx": [ - "jsx" - ] -} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/index.js b/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/index.js deleted file mode 100644 index cc2d155..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/index.js +++ /dev/null @@ -1,75 +0,0 @@ - -// types[extension] = type -exports.types = Object.create(null) -// extensions[type] = [extensions] -exports.extensions = Object.create(null) -// define more mime types -exports.define = define - -// store the json files -exports.json = { - mime: require('./mime.json'), - node: require('./node.json'), - custom: require('./custom.json'), -} - -exports.lookup = function (string) { - if (!string || typeof string !== "string") return false - string = string.replace(/.*[\.\/\\]/, '').toLowerCase() - if (!string) return false - return exports.types[string] || false -} - -exports.extension = function (type) { - if (!type || typeof type !== "string") return false - type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/) - if (!type) return false - var exts = exports.extensions[type[1].toLowerCase()] - if (!exts || !exts.length) return false - return exts[0] -} - -// type has to be an exact mime type -exports.charset = function (type) { - // special cases - switch (type) { - case 'application/json': return 'UTF-8' - case 'application/javascript': return 'UTF-8' - } - - // default text/* to utf-8 - if (/^text\//.test(type)) return 'UTF-8' - - return false -} - -// backwards compatibility -exports.charsets = { - lookup: exports.charset -} - -exports.contentType = function (type) { - if (!type || typeof type !== "string") return false - if (!~type.indexOf('/')) type = exports.lookup(type) - if (!type) return false - if (!~type.indexOf('charset')) { - var charset = exports.charset(type) - if (charset) type += '; charset=' + charset.toLowerCase() - } - return type -} - -define(exports.json.mime) -define(exports.json.node) -define(exports.json.custom) - -function define(json) { - Object.keys(json).forEach(function (type) { - var exts = json[type] || [] - exports.extensions[type] = exports.extensions[type] || [] - exts.forEach(function (ext) { - if (!~exports.extensions[type].indexOf(ext)) exports.extensions[type].push(ext) - exports.types[ext] = type - }) - }) -} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/mime.json b/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/mime.json deleted file mode 100644 index f445a86..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/mime.json +++ /dev/null @@ -1,3317 +0,0 @@ -{ - "application/1d-interleaved-parityfec": [], - "application/3gpp-ims+xml": [], - "application/activemessage": [], - "application/andrew-inset": [ - "ez" - ], - "application/applefile": [], - "application/applixware": [ - "aw" - ], - "application/atom+xml": [ - "atom" - ], - "application/atomcat+xml": [ - "atomcat" - ], - "application/atomicmail": [], - "application/atomsvc+xml": [ - "atomsvc" - ], - "application/auth-policy+xml": [], - "application/batch-smtp": [], - "application/beep+xml": [], - "application/calendar+xml": [], - "application/cals-1840": [], - "application/ccmp+xml": [], - "application/ccxml+xml": [ - "ccxml" - ], - "application/cdmi-capability": [ - "cdmia" - ], - "application/cdmi-container": [ - "cdmic" - ], - "application/cdmi-domain": [ - "cdmid" - ], - "application/cdmi-object": [ - "cdmio" - ], - "application/cdmi-queue": [ - "cdmiq" - ], - "application/cea-2018+xml": [], - "application/cellml+xml": [], - "application/cfw": [], - "application/cnrp+xml": [], - "application/commonground": [], - "application/conference-info+xml": [], - "application/cpl+xml": [], - "application/csta+xml": [], - "application/cstadata+xml": [], - "application/cu-seeme": [ - "cu" - ], - "application/cybercash": [], - "application/davmount+xml": [ - "davmount" - ], - "application/dca-rft": [], - "application/dec-dx": [], - "application/dialog-info+xml": [], - "application/dicom": [], - "application/dns": [], - "application/docbook+xml": [ - "dbk" - ], - "application/dskpp+xml": [], - "application/dssc+der": [ - "dssc" - ], - "application/dssc+xml": [ - "xdssc" - ], - "application/dvcs": [], - "application/ecmascript": [ - "ecma" - ], - "application/edi-consent": [], - "application/edi-x12": [], - "application/edifact": [], - "application/emma+xml": [ - "emma" - ], - "application/epp+xml": [], - "application/epub+zip": [ - "epub" - ], - "application/eshop": [], - "application/example": [], - "application/exi": [ - "exi" - ], - "application/fastinfoset": [], - "application/fastsoap": [], - "application/fits": [], - "application/font-tdpfr": [ - "pfr" - ], - "application/framework-attributes+xml": [], - "application/gml+xml": [ - "gml" - ], - "application/gpx+xml": [ - "gpx" - ], - "application/gxf": [ - "gxf" - ], - "application/h224": [], - "application/held+xml": [], - "application/http": [], - "application/hyperstudio": [ - "stk" - ], - "application/ibe-key-request+xml": [], - "application/ibe-pkg-reply+xml": [], - "application/ibe-pp-data": [], - "application/iges": [], - "application/im-iscomposing+xml": [], - "application/index": [], - "application/index.cmd": [], - "application/index.obj": [], - "application/index.response": [], - "application/index.vnd": [], - "application/inkml+xml": [ - "ink", - "inkml" - ], - "application/iotp": [], - "application/ipfix": [ - "ipfix" - ], - "application/ipp": [], - "application/isup": [], - "application/java-archive": [ - "jar" - ], - "application/java-serialized-object": [ - "ser" - ], - "application/java-vm": [ - "class" - ], - "application/javascript": [ - "js" - ], - "application/json": [ - "json" - ], - "application/jsonml+json": [ - "jsonml" - ], - "application/kpml-request+xml": [], - "application/kpml-response+xml": [], - "application/lost+xml": [ - "lostxml" - ], - "application/mac-binhex40": [ - "hqx" - ], - "application/mac-compactpro": [ - "cpt" - ], - "application/macwriteii": [], - "application/mads+xml": [ - "mads" - ], - "application/marc": [ - "mrc" - ], - "application/marcxml+xml": [ - "mrcx" - ], - "application/mathematica": [ - "ma", - "nb", - "mb" - ], - "application/mathml-content+xml": [], - "application/mathml-presentation+xml": [], - "application/mathml+xml": [ - "mathml" - ], - "application/mbms-associated-procedure-description+xml": [], - "application/mbms-deregister+xml": [], - "application/mbms-envelope+xml": [], - "application/mbms-msk+xml": [], - "application/mbms-msk-response+xml": [], - "application/mbms-protection-description+xml": [], - "application/mbms-reception-report+xml": [], - "application/mbms-register+xml": [], - "application/mbms-register-response+xml": [], - "application/mbms-user-service-description+xml": [], - "application/mbox": [ - "mbox" - ], - "application/media_control+xml": [], - "application/mediaservercontrol+xml": [ - "mscml" - ], - "application/metalink+xml": [ - "metalink" - ], - "application/metalink4+xml": [ - "meta4" - ], - "application/mets+xml": [ - "mets" - ], - "application/mikey": [], - "application/mods+xml": [ - "mods" - ], - "application/moss-keys": [], - "application/moss-signature": [], - "application/mosskey-data": [], - "application/mosskey-request": [], - "application/mp21": [ - "m21", - "mp21" - ], - "application/mp4": [ - "mp4s" - ], - "application/mpeg4-generic": [], - "application/mpeg4-iod": [], - "application/mpeg4-iod-xmt": [], - "application/msc-ivr+xml": [], - "application/msc-mixer+xml": [], - "application/msword": [ - "doc", - "dot" - ], - "application/mxf": [ - "mxf" - ], - "application/nasdata": [], - "application/news-checkgroups": [], - "application/news-groupinfo": [], - "application/news-transmission": [], - "application/nss": [], - "application/ocsp-request": [], - "application/ocsp-response": [], - "application/octet-stream": [ - "bin", - "dms", - "lrf", - "mar", - "so", - "dist", - "distz", - "pkg", - "bpk", - "dump", - "elc", - "deploy" - ], - "application/oda": [ - "oda" - ], - "application/oebps-package+xml": [ - "opf" - ], - "application/ogg": [ - "ogx" - ], - "application/omdoc+xml": [ - "omdoc" - ], - "application/onenote": [ - "onetoc", - "onetoc2", - "onetmp", - "onepkg" - ], - "application/oxps": [ - "oxps" - ], - "application/parityfec": [], - "application/patch-ops-error+xml": [ - "xer" - ], - "application/pdf": [ - "pdf" - ], - "application/pgp-encrypted": [ - "pgp" - ], - "application/pgp-keys": [], - "application/pgp-signature": [ - "asc", - "sig" - ], - "application/pics-rules": [ - "prf" - ], - "application/pidf+xml": [], - "application/pidf-diff+xml": [], - "application/pkcs10": [ - "p10" - ], - "application/pkcs7-mime": [ - "p7m", - "p7c" - ], - "application/pkcs7-signature": [ - "p7s" - ], - "application/pkcs8": [ - "p8" - ], - "application/pkix-attr-cert": [ - "ac" - ], - "application/pkix-cert": [ - "cer" - ], - "application/pkix-crl": [ - "crl" - ], - "application/pkix-pkipath": [ - "pkipath" - ], - "application/pkixcmp": [ - "pki" - ], - "application/pls+xml": [ - "pls" - ], - "application/poc-settings+xml": [], - "application/postscript": [ - "ai", - "eps", - "ps" - ], - "application/prs.alvestrand.titrax-sheet": [], - "application/prs.cww": [ - "cww" - ], - "application/prs.nprend": [], - "application/prs.plucker": [], - "application/prs.rdf-xml-crypt": [], - "application/prs.xsf+xml": [], - "application/pskc+xml": [ - "pskcxml" - ], - "application/qsig": [], - "application/rdf+xml": [ - "rdf" - ], - "application/reginfo+xml": [ - "rif" - ], - "application/relax-ng-compact-syntax": [ - "rnc" - ], - "application/remote-printing": [], - "application/resource-lists+xml": [ - "rl" - ], - "application/resource-lists-diff+xml": [ - "rld" - ], - "application/riscos": [], - "application/rlmi+xml": [], - "application/rls-services+xml": [ - "rs" - ], - "application/rpki-ghostbusters": [ - "gbr" - ], - "application/rpki-manifest": [ - "mft" - ], - "application/rpki-roa": [ - "roa" - ], - "application/rpki-updown": [], - "application/rsd+xml": [ - "rsd" - ], - "application/rss+xml": [ - "rss" - ], - "application/rtf": [ - "rtf" - ], - "application/rtx": [], - "application/samlassertion+xml": [], - "application/samlmetadata+xml": [], - "application/sbml+xml": [ - "sbml" - ], - "application/scvp-cv-request": [ - "scq" - ], - "application/scvp-cv-response": [ - "scs" - ], - "application/scvp-vp-request": [ - "spq" - ], - "application/scvp-vp-response": [ - "spp" - ], - "application/sdp": [ - "sdp" - ], - "application/set-payment": [], - "application/set-payment-initiation": [ - "setpay" - ], - "application/set-registration": [], - "application/set-registration-initiation": [ - "setreg" - ], - "application/sgml": [], - "application/sgml-open-catalog": [], - "application/shf+xml": [ - "shf" - ], - "application/sieve": [], - "application/simple-filter+xml": [], - "application/simple-message-summary": [], - "application/simplesymbolcontainer": [], - "application/slate": [], - "application/smil": [], - "application/smil+xml": [ - "smi", - "smil" - ], - "application/soap+fastinfoset": [], - "application/soap+xml": [], - "application/sparql-query": [ - "rq" - ], - "application/sparql-results+xml": [ - "srx" - ], - "application/spirits-event+xml": [], - "application/srgs": [ - "gram" - ], - "application/srgs+xml": [ - "grxml" - ], - "application/sru+xml": [ - "sru" - ], - "application/ssdl+xml": [ - "ssdl" - ], - "application/ssml+xml": [ - "ssml" - ], - "application/tamp-apex-update": [], - "application/tamp-apex-update-confirm": [], - "application/tamp-community-update": [], - "application/tamp-community-update-confirm": [], - "application/tamp-error": [], - "application/tamp-sequence-adjust": [], - "application/tamp-sequence-adjust-confirm": [], - "application/tamp-status-query": [], - "application/tamp-status-response": [], - "application/tamp-update": [], - "application/tamp-update-confirm": [], - "application/tei+xml": [ - "tei", - "teicorpus" - ], - "application/thraud+xml": [ - "tfi" - ], - "application/timestamp-query": [], - "application/timestamp-reply": [], - "application/timestamped-data": [ - "tsd" - ], - "application/tve-trigger": [], - "application/ulpfec": [], - "application/vcard+xml": [], - "application/vemmi": [], - "application/vividence.scriptfile": [], - "application/vnd.3gpp.bsf+xml": [], - "application/vnd.3gpp.pic-bw-large": [ - "plb" - ], - "application/vnd.3gpp.pic-bw-small": [ - "psb" - ], - "application/vnd.3gpp.pic-bw-var": [ - "pvb" - ], - "application/vnd.3gpp.sms": [], - "application/vnd.3gpp2.bcmcsinfo+xml": [], - "application/vnd.3gpp2.sms": [], - "application/vnd.3gpp2.tcap": [ - "tcap" - ], - "application/vnd.3m.post-it-notes": [ - "pwn" - ], - "application/vnd.accpac.simply.aso": [ - "aso" - ], - "application/vnd.accpac.simply.imp": [ - "imp" - ], - "application/vnd.acucobol": [ - "acu" - ], - "application/vnd.acucorp": [ - "atc", - "acutc" - ], - "application/vnd.adobe.air-application-installer-package+zip": [ - "air" - ], - "application/vnd.adobe.formscentral.fcdt": [ - "fcdt" - ], - "application/vnd.adobe.fxp": [ - "fxp", - "fxpl" - ], - "application/vnd.adobe.partial-upload": [], - "application/vnd.adobe.xdp+xml": [ - "xdp" - ], - "application/vnd.adobe.xfdf": [ - "xfdf" - ], - "application/vnd.aether.imp": [], - "application/vnd.ah-barcode": [], - "application/vnd.ahead.space": [ - "ahead" - ], - "application/vnd.airzip.filesecure.azf": [ - "azf" - ], - "application/vnd.airzip.filesecure.azs": [ - "azs" - ], - "application/vnd.amazon.ebook": [ - "azw" - ], - "application/vnd.americandynamics.acc": [ - "acc" - ], - "application/vnd.amiga.ami": [ - "ami" - ], - "application/vnd.amundsen.maze+xml": [], - "application/vnd.android.package-archive": [ - "apk" - ], - "application/vnd.anser-web-certificate-issue-initiation": [ - "cii" - ], - "application/vnd.anser-web-funds-transfer-initiation": [ - "fti" - ], - "application/vnd.antix.game-component": [ - "atx" - ], - "application/vnd.apple.installer+xml": [ - "mpkg" - ], - "application/vnd.apple.mpegurl": [ - "m3u8" - ], - "application/vnd.arastra.swi": [], - "application/vnd.aristanetworks.swi": [ - "swi" - ], - "application/vnd.astraea-software.iota": [ - "iota" - ], - "application/vnd.audiograph": [ - "aep" - ], - "application/vnd.autopackage": [], - "application/vnd.avistar+xml": [], - "application/vnd.blueice.multipass": [ - "mpm" - ], - "application/vnd.bluetooth.ep.oob": [], - "application/vnd.bmi": [ - "bmi" - ], - "application/vnd.businessobjects": [ - "rep" - ], - "application/vnd.cab-jscript": [], - "application/vnd.canon-cpdl": [], - "application/vnd.canon-lips": [], - "application/vnd.cendio.thinlinc.clientconf": [], - "application/vnd.chemdraw+xml": [ - "cdxml" - ], - "application/vnd.chipnuts.karaoke-mmd": [ - "mmd" - ], - "application/vnd.cinderella": [ - "cdy" - ], - "application/vnd.cirpack.isdn-ext": [], - "application/vnd.claymore": [ - "cla" - ], - "application/vnd.cloanto.rp9": [ - "rp9" - ], - "application/vnd.clonk.c4group": [ - "c4g", - "c4d", - "c4f", - "c4p", - "c4u" - ], - "application/vnd.cluetrust.cartomobile-config": [ - "c11amc" - ], - "application/vnd.cluetrust.cartomobile-config-pkg": [ - "c11amz" - ], - "application/vnd.collection+json": [], - "application/vnd.commerce-battelle": [], - "application/vnd.commonspace": [ - "csp" - ], - "application/vnd.contact.cmsg": [ - "cdbcmsg" - ], - "application/vnd.cosmocaller": [ - "cmc" - ], - "application/vnd.crick.clicker": [ - "clkx" - ], - "application/vnd.crick.clicker.keyboard": [ - "clkk" - ], - "application/vnd.crick.clicker.palette": [ - "clkp" - ], - "application/vnd.crick.clicker.template": [ - "clkt" - ], - "application/vnd.crick.clicker.wordbank": [ - "clkw" - ], - "application/vnd.criticaltools.wbs+xml": [ - "wbs" - ], - "application/vnd.ctc-posml": [ - "pml" - ], - "application/vnd.ctct.ws+xml": [], - "application/vnd.cups-pdf": [], - "application/vnd.cups-postscript": [], - "application/vnd.cups-ppd": [ - "ppd" - ], - "application/vnd.cups-raster": [], - "application/vnd.cups-raw": [], - "application/vnd.curl": [], - "application/vnd.curl.car": [ - "car" - ], - "application/vnd.curl.pcurl": [ - "pcurl" - ], - "application/vnd.cybank": [], - "application/vnd.dart": [ - "dart" - ], - "application/vnd.data-vision.rdz": [ - "rdz" - ], - "application/vnd.dece.data": [ - "uvf", - "uvvf", - "uvd", - "uvvd" - ], - "application/vnd.dece.ttml+xml": [ - "uvt", - "uvvt" - ], - "application/vnd.dece.unspecified": [ - "uvx", - "uvvx" - ], - "application/vnd.dece.zip": [ - "uvz", - "uvvz" - ], - "application/vnd.denovo.fcselayout-link": [ - "fe_launch" - ], - "application/vnd.dir-bi.plate-dl-nosuffix": [], - "application/vnd.dna": [ - "dna" - ], - "application/vnd.dolby.mlp": [ - "mlp" - ], - "application/vnd.dolby.mobile.1": [], - "application/vnd.dolby.mobile.2": [], - "application/vnd.dpgraph": [ - "dpg" - ], - "application/vnd.dreamfactory": [ - "dfac" - ], - "application/vnd.ds-keypoint": [ - "kpxx" - ], - "application/vnd.dvb.ait": [ - "ait" - ], - "application/vnd.dvb.dvbj": [], - "application/vnd.dvb.esgcontainer": [], - "application/vnd.dvb.ipdcdftnotifaccess": [], - "application/vnd.dvb.ipdcesgaccess": [], - "application/vnd.dvb.ipdcesgaccess2": [], - "application/vnd.dvb.ipdcesgpdd": [], - "application/vnd.dvb.ipdcroaming": [], - "application/vnd.dvb.iptv.alfec-base": [], - "application/vnd.dvb.iptv.alfec-enhancement": [], - "application/vnd.dvb.notif-aggregate-root+xml": [], - "application/vnd.dvb.notif-container+xml": [], - "application/vnd.dvb.notif-generic+xml": [], - "application/vnd.dvb.notif-ia-msglist+xml": [], - "application/vnd.dvb.notif-ia-registration-request+xml": [], - "application/vnd.dvb.notif-ia-registration-response+xml": [], - "application/vnd.dvb.notif-init+xml": [], - "application/vnd.dvb.pfr": [], - "application/vnd.dvb.service": [ - "svc" - ], - "application/vnd.dxr": [], - "application/vnd.dynageo": [ - "geo" - ], - "application/vnd.easykaraoke.cdgdownload": [], - "application/vnd.ecdis-update": [], - "application/vnd.ecowin.chart": [ - "mag" - ], - "application/vnd.ecowin.filerequest": [], - "application/vnd.ecowin.fileupdate": [], - "application/vnd.ecowin.series": [], - "application/vnd.ecowin.seriesrequest": [], - "application/vnd.ecowin.seriesupdate": [], - "application/vnd.emclient.accessrequest+xml": [], - "application/vnd.enliven": [ - "nml" - ], - "application/vnd.eprints.data+xml": [], - "application/vnd.epson.esf": [ - "esf" - ], - "application/vnd.epson.msf": [ - "msf" - ], - "application/vnd.epson.quickanime": [ - "qam" - ], - "application/vnd.epson.salt": [ - "slt" - ], - "application/vnd.epson.ssf": [ - "ssf" - ], - "application/vnd.ericsson.quickcall": [], - "application/vnd.eszigno3+xml": [ - "es3", - "et3" - ], - "application/vnd.etsi.aoc+xml": [], - "application/vnd.etsi.cug+xml": [], - "application/vnd.etsi.iptvcommand+xml": [], - "application/vnd.etsi.iptvdiscovery+xml": [], - "application/vnd.etsi.iptvprofile+xml": [], - "application/vnd.etsi.iptvsad-bc+xml": [], - "application/vnd.etsi.iptvsad-cod+xml": [], - "application/vnd.etsi.iptvsad-npvr+xml": [], - "application/vnd.etsi.iptvservice+xml": [], - "application/vnd.etsi.iptvsync+xml": [], - "application/vnd.etsi.iptvueprofile+xml": [], - "application/vnd.etsi.mcid+xml": [], - "application/vnd.etsi.overload-control-policy-dataset+xml": [], - "application/vnd.etsi.sci+xml": [], - "application/vnd.etsi.simservs+xml": [], - "application/vnd.etsi.tsl+xml": [], - "application/vnd.etsi.tsl.der": [], - "application/vnd.eudora.data": [], - "application/vnd.ezpix-album": [ - "ez2" - ], - "application/vnd.ezpix-package": [ - "ez3" - ], - "application/vnd.f-secure.mobile": [], - "application/vnd.fdf": [ - "fdf" - ], - "application/vnd.fdsn.mseed": [ - "mseed" - ], - "application/vnd.fdsn.seed": [ - "seed", - "dataless" - ], - "application/vnd.ffsns": [], - "application/vnd.fints": [], - "application/vnd.flographit": [ - "gph" - ], - "application/vnd.fluxtime.clip": [ - "ftc" - ], - "application/vnd.font-fontforge-sfd": [], - "application/vnd.framemaker": [ - "fm", - "frame", - "maker", - "book" - ], - "application/vnd.frogans.fnc": [ - "fnc" - ], - "application/vnd.frogans.ltf": [ - "ltf" - ], - "application/vnd.fsc.weblaunch": [ - "fsc" - ], - "application/vnd.fujitsu.oasys": [ - "oas" - ], - "application/vnd.fujitsu.oasys2": [ - "oa2" - ], - "application/vnd.fujitsu.oasys3": [ - "oa3" - ], - "application/vnd.fujitsu.oasysgp": [ - "fg5" - ], - "application/vnd.fujitsu.oasysprs": [ - "bh2" - ], - "application/vnd.fujixerox.art-ex": [], - "application/vnd.fujixerox.art4": [], - "application/vnd.fujixerox.hbpl": [], - "application/vnd.fujixerox.ddd": [ - "ddd" - ], - "application/vnd.fujixerox.docuworks": [ - "xdw" - ], - "application/vnd.fujixerox.docuworks.binder": [ - "xbd" - ], - "application/vnd.fut-misnet": [], - "application/vnd.fuzzysheet": [ - "fzs" - ], - "application/vnd.genomatix.tuxedo": [ - "txd" - ], - "application/vnd.geocube+xml": [], - "application/vnd.geogebra.file": [ - "ggb" - ], - "application/vnd.geogebra.tool": [ - "ggt" - ], - "application/vnd.geometry-explorer": [ - "gex", - "gre" - ], - "application/vnd.geonext": [ - "gxt" - ], - "application/vnd.geoplan": [ - "g2w" - ], - "application/vnd.geospace": [ - "g3w" - ], - "application/vnd.globalplatform.card-content-mgt": [], - "application/vnd.globalplatform.card-content-mgt-response": [], - "application/vnd.gmx": [ - "gmx" - ], - "application/vnd.google-earth.kml+xml": [ - "kml" - ], - "application/vnd.google-earth.kmz": [ - "kmz" - ], - "application/vnd.grafeq": [ - "gqf", - "gqs" - ], - "application/vnd.gridmp": [], - "application/vnd.groove-account": [ - "gac" - ], - "application/vnd.groove-help": [ - "ghf" - ], - "application/vnd.groove-identity-message": [ - "gim" - ], - "application/vnd.groove-injector": [ - "grv" - ], - "application/vnd.groove-tool-message": [ - "gtm" - ], - "application/vnd.groove-tool-template": [ - "tpl" - ], - "application/vnd.groove-vcard": [ - "vcg" - ], - "application/vnd.hal+json": [], - "application/vnd.hal+xml": [ - "hal" - ], - "application/vnd.handheld-entertainment+xml": [ - "zmm" - ], - "application/vnd.hbci": [ - "hbci" - ], - "application/vnd.hcl-bireports": [], - "application/vnd.hhe.lesson-player": [ - "les" - ], - "application/vnd.hp-hpgl": [ - "hpgl" - ], - "application/vnd.hp-hpid": [ - "hpid" - ], - "application/vnd.hp-hps": [ - "hps" - ], - "application/vnd.hp-jlyt": [ - "jlt" - ], - "application/vnd.hp-pcl": [ - "pcl" - ], - "application/vnd.hp-pclxl": [ - "pclxl" - ], - "application/vnd.httphone": [], - "application/vnd.hzn-3d-crossword": [], - "application/vnd.ibm.afplinedata": [], - "application/vnd.ibm.electronic-media": [], - "application/vnd.ibm.minipay": [ - "mpy" - ], - "application/vnd.ibm.modcap": [ - "afp", - "listafp", - "list3820" - ], - "application/vnd.ibm.rights-management": [ - "irm" - ], - "application/vnd.ibm.secure-container": [ - "sc" - ], - "application/vnd.iccprofile": [ - "icc", - "icm" - ], - "application/vnd.igloader": [ - "igl" - ], - "application/vnd.immervision-ivp": [ - "ivp" - ], - "application/vnd.immervision-ivu": [ - "ivu" - ], - "application/vnd.informedcontrol.rms+xml": [], - "application/vnd.informix-visionary": [], - "application/vnd.infotech.project": [], - "application/vnd.infotech.project+xml": [], - "application/vnd.innopath.wamp.notification": [], - "application/vnd.insors.igm": [ - "igm" - ], - "application/vnd.intercon.formnet": [ - "xpw", - "xpx" - ], - "application/vnd.intergeo": [ - "i2g" - ], - "application/vnd.intertrust.digibox": [], - "application/vnd.intertrust.nncp": [], - "application/vnd.intu.qbo": [ - "qbo" - ], - "application/vnd.intu.qfx": [ - "qfx" - ], - "application/vnd.iptc.g2.conceptitem+xml": [], - "application/vnd.iptc.g2.knowledgeitem+xml": [], - "application/vnd.iptc.g2.newsitem+xml": [], - "application/vnd.iptc.g2.newsmessage+xml": [], - "application/vnd.iptc.g2.packageitem+xml": [], - "application/vnd.iptc.g2.planningitem+xml": [], - "application/vnd.ipunplugged.rcprofile": [ - "rcprofile" - ], - "application/vnd.irepository.package+xml": [ - "irp" - ], - "application/vnd.is-xpr": [ - "xpr" - ], - "application/vnd.isac.fcs": [ - "fcs" - ], - "application/vnd.jam": [ - "jam" - ], - "application/vnd.japannet-directory-service": [], - "application/vnd.japannet-jpnstore-wakeup": [], - "application/vnd.japannet-payment-wakeup": [], - "application/vnd.japannet-registration": [], - "application/vnd.japannet-registration-wakeup": [], - "application/vnd.japannet-setstore-wakeup": [], - "application/vnd.japannet-verification": [], - "application/vnd.japannet-verification-wakeup": [], - "application/vnd.jcp.javame.midlet-rms": [ - "rms" - ], - "application/vnd.jisp": [ - "jisp" - ], - "application/vnd.joost.joda-archive": [ - "joda" - ], - "application/vnd.kahootz": [ - "ktz", - "ktr" - ], - "application/vnd.kde.karbon": [ - "karbon" - ], - "application/vnd.kde.kchart": [ - "chrt" - ], - "application/vnd.kde.kformula": [ - "kfo" - ], - "application/vnd.kde.kivio": [ - "flw" - ], - "application/vnd.kde.kontour": [ - "kon" - ], - "application/vnd.kde.kpresenter": [ - "kpr", - "kpt" - ], - "application/vnd.kde.kspread": [ - "ksp" - ], - "application/vnd.kde.kword": [ - "kwd", - "kwt" - ], - "application/vnd.kenameaapp": [ - "htke" - ], - "application/vnd.kidspiration": [ - "kia" - ], - "application/vnd.kinar": [ - "kne", - "knp" - ], - "application/vnd.koan": [ - "skp", - "skd", - "skt", - "skm" - ], - "application/vnd.kodak-descriptor": [ - "sse" - ], - "application/vnd.las.las+xml": [ - "lasxml" - ], - "application/vnd.liberty-request+xml": [], - "application/vnd.llamagraphics.life-balance.desktop": [ - "lbd" - ], - "application/vnd.llamagraphics.life-balance.exchange+xml": [ - "lbe" - ], - "application/vnd.lotus-1-2-3": [ - "123" - ], - "application/vnd.lotus-approach": [ - "apr" - ], - "application/vnd.lotus-freelance": [ - "pre" - ], - "application/vnd.lotus-notes": [ - "nsf" - ], - "application/vnd.lotus-organizer": [ - "org" - ], - "application/vnd.lotus-screencam": [ - "scm" - ], - "application/vnd.lotus-wordpro": [ - "lwp" - ], - "application/vnd.macports.portpkg": [ - "portpkg" - ], - "application/vnd.marlin.drm.actiontoken+xml": [], - "application/vnd.marlin.drm.conftoken+xml": [], - "application/vnd.marlin.drm.license+xml": [], - "application/vnd.marlin.drm.mdcf": [], - "application/vnd.mcd": [ - "mcd" - ], - "application/vnd.medcalcdata": [ - "mc1" - ], - "application/vnd.mediastation.cdkey": [ - "cdkey" - ], - "application/vnd.meridian-slingshot": [], - "application/vnd.mfer": [ - "mwf" - ], - "application/vnd.mfmp": [ - "mfm" - ], - "application/vnd.micrografx.flo": [ - "flo" - ], - "application/vnd.micrografx.igx": [ - "igx" - ], - "application/vnd.mif": [ - "mif" - ], - "application/vnd.minisoft-hp3000-save": [], - "application/vnd.mitsubishi.misty-guard.trustweb": [], - "application/vnd.mobius.daf": [ - "daf" - ], - "application/vnd.mobius.dis": [ - "dis" - ], - "application/vnd.mobius.mbk": [ - "mbk" - ], - "application/vnd.mobius.mqy": [ - "mqy" - ], - "application/vnd.mobius.msl": [ - "msl" - ], - "application/vnd.mobius.plc": [ - "plc" - ], - "application/vnd.mobius.txf": [ - "txf" - ], - "application/vnd.mophun.application": [ - "mpn" - ], - "application/vnd.mophun.certificate": [ - "mpc" - ], - "application/vnd.motorola.flexsuite": [], - "application/vnd.motorola.flexsuite.adsi": [], - "application/vnd.motorola.flexsuite.fis": [], - "application/vnd.motorola.flexsuite.gotap": [], - "application/vnd.motorola.flexsuite.kmr": [], - "application/vnd.motorola.flexsuite.ttc": [], - "application/vnd.motorola.flexsuite.wem": [], - "application/vnd.motorola.iprm": [], - "application/vnd.mozilla.xul+xml": [ - "xul" - ], - "application/vnd.ms-artgalry": [ - "cil" - ], - "application/vnd.ms-asf": [], - "application/vnd.ms-cab-compressed": [ - "cab" - ], - "application/vnd.ms-color.iccprofile": [], - "application/vnd.ms-excel": [ - "xls", - "xlm", - "xla", - "xlc", - "xlt", - "xlw" - ], - "application/vnd.ms-excel.addin.macroenabled.12": [ - "xlam" - ], - "application/vnd.ms-excel.sheet.binary.macroenabled.12": [ - "xlsb" - ], - "application/vnd.ms-excel.sheet.macroenabled.12": [ - "xlsm" - ], - "application/vnd.ms-excel.template.macroenabled.12": [ - "xltm" - ], - "application/vnd.ms-fontobject": [ - "eot" - ], - "application/vnd.ms-htmlhelp": [ - "chm" - ], - "application/vnd.ms-ims": [ - "ims" - ], - "application/vnd.ms-lrm": [ - "lrm" - ], - "application/vnd.ms-office.activex+xml": [], - "application/vnd.ms-officetheme": [ - "thmx" - ], - "application/vnd.ms-opentype": [], - "application/vnd.ms-package.obfuscated-opentype": [], - "application/vnd.ms-pki.seccat": [ - "cat" - ], - "application/vnd.ms-pki.stl": [ - "stl" - ], - "application/vnd.ms-playready.initiator+xml": [], - "application/vnd.ms-powerpoint": [ - "ppt", - "pps", - "pot" - ], - "application/vnd.ms-powerpoint.addin.macroenabled.12": [ - "ppam" - ], - "application/vnd.ms-powerpoint.presentation.macroenabled.12": [ - "pptm" - ], - "application/vnd.ms-powerpoint.slide.macroenabled.12": [ - "sldm" - ], - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": [ - "ppsm" - ], - "application/vnd.ms-powerpoint.template.macroenabled.12": [ - "potm" - ], - "application/vnd.ms-printing.printticket+xml": [], - "application/vnd.ms-project": [ - "mpp", - "mpt" - ], - "application/vnd.ms-tnef": [], - "application/vnd.ms-wmdrm.lic-chlg-req": [], - "application/vnd.ms-wmdrm.lic-resp": [], - "application/vnd.ms-wmdrm.meter-chlg-req": [], - "application/vnd.ms-wmdrm.meter-resp": [], - "application/vnd.ms-word.document.macroenabled.12": [ - "docm" - ], - "application/vnd.ms-word.template.macroenabled.12": [ - "dotm" - ], - "application/vnd.ms-works": [ - "wps", - "wks", - "wcm", - "wdb" - ], - "application/vnd.ms-wpl": [ - "wpl" - ], - "application/vnd.ms-xpsdocument": [ - "xps" - ], - "application/vnd.mseq": [ - "mseq" - ], - "application/vnd.msign": [], - "application/vnd.multiad.creator": [], - "application/vnd.multiad.creator.cif": [], - "application/vnd.music-niff": [], - "application/vnd.musician": [ - "mus" - ], - "application/vnd.muvee.style": [ - "msty" - ], - "application/vnd.mynfc": [ - "taglet" - ], - "application/vnd.ncd.control": [], - "application/vnd.ncd.reference": [], - "application/vnd.nervana": [], - "application/vnd.netfpx": [], - "application/vnd.neurolanguage.nlu": [ - "nlu" - ], - "application/vnd.nitf": [ - "ntf", - "nitf" - ], - "application/vnd.noblenet-directory": [ - "nnd" - ], - "application/vnd.noblenet-sealer": [ - "nns" - ], - "application/vnd.noblenet-web": [ - "nnw" - ], - "application/vnd.nokia.catalogs": [], - "application/vnd.nokia.conml+wbxml": [], - "application/vnd.nokia.conml+xml": [], - "application/vnd.nokia.isds-radio-presets": [], - "application/vnd.nokia.iptv.config+xml": [], - "application/vnd.nokia.landmark+wbxml": [], - "application/vnd.nokia.landmark+xml": [], - "application/vnd.nokia.landmarkcollection+xml": [], - "application/vnd.nokia.n-gage.ac+xml": [], - "application/vnd.nokia.n-gage.data": [ - "ngdat" - ], - "application/vnd.nokia.ncd": [], - "application/vnd.nokia.pcd+wbxml": [], - "application/vnd.nokia.pcd+xml": [], - "application/vnd.nokia.radio-preset": [ - "rpst" - ], - "application/vnd.nokia.radio-presets": [ - "rpss" - ], - "application/vnd.novadigm.edm": [ - "edm" - ], - "application/vnd.novadigm.edx": [ - "edx" - ], - "application/vnd.novadigm.ext": [ - "ext" - ], - "application/vnd.ntt-local.file-transfer": [], - "application/vnd.ntt-local.sip-ta_remote": [], - "application/vnd.ntt-local.sip-ta_tcp_stream": [], - "application/vnd.oasis.opendocument.chart": [ - "odc" - ], - "application/vnd.oasis.opendocument.chart-template": [ - "otc" - ], - "application/vnd.oasis.opendocument.database": [ - "odb" - ], - "application/vnd.oasis.opendocument.formula": [ - "odf" - ], - "application/vnd.oasis.opendocument.formula-template": [ - "odft" - ], - "application/vnd.oasis.opendocument.graphics": [ - "odg" - ], - "application/vnd.oasis.opendocument.graphics-template": [ - "otg" - ], - "application/vnd.oasis.opendocument.image": [ - "odi" - ], - "application/vnd.oasis.opendocument.image-template": [ - "oti" - ], - "application/vnd.oasis.opendocument.presentation": [ - "odp" - ], - "application/vnd.oasis.opendocument.presentation-template": [ - "otp" - ], - "application/vnd.oasis.opendocument.spreadsheet": [ - "ods" - ], - "application/vnd.oasis.opendocument.spreadsheet-template": [ - "ots" - ], - "application/vnd.oasis.opendocument.text": [ - "odt" - ], - "application/vnd.oasis.opendocument.text-master": [ - "odm" - ], - "application/vnd.oasis.opendocument.text-template": [ - "ott" - ], - "application/vnd.oasis.opendocument.text-web": [ - "oth" - ], - "application/vnd.obn": [], - "application/vnd.oftn.l10n+json": [], - "application/vnd.oipf.contentaccessdownload+xml": [], - "application/vnd.oipf.contentaccessstreaming+xml": [], - "application/vnd.oipf.cspg-hexbinary": [], - "application/vnd.oipf.dae.svg+xml": [], - "application/vnd.oipf.dae.xhtml+xml": [], - "application/vnd.oipf.mippvcontrolmessage+xml": [], - "application/vnd.oipf.pae.gem": [], - "application/vnd.oipf.spdiscovery+xml": [], - "application/vnd.oipf.spdlist+xml": [], - "application/vnd.oipf.ueprofile+xml": [], - "application/vnd.oipf.userprofile+xml": [], - "application/vnd.olpc-sugar": [ - "xo" - ], - "application/vnd.oma-scws-config": [], - "application/vnd.oma-scws-http-request": [], - "application/vnd.oma-scws-http-response": [], - "application/vnd.oma.bcast.associated-procedure-parameter+xml": [], - "application/vnd.oma.bcast.drm-trigger+xml": [], - "application/vnd.oma.bcast.imd+xml": [], - "application/vnd.oma.bcast.ltkm": [], - "application/vnd.oma.bcast.notification+xml": [], - "application/vnd.oma.bcast.provisioningtrigger": [], - "application/vnd.oma.bcast.sgboot": [], - "application/vnd.oma.bcast.sgdd+xml": [], - "application/vnd.oma.bcast.sgdu": [], - "application/vnd.oma.bcast.simple-symbol-container": [], - "application/vnd.oma.bcast.smartcard-trigger+xml": [], - "application/vnd.oma.bcast.sprov+xml": [], - "application/vnd.oma.bcast.stkm": [], - "application/vnd.oma.cab-address-book+xml": [], - "application/vnd.oma.cab-feature-handler+xml": [], - "application/vnd.oma.cab-pcc+xml": [], - "application/vnd.oma.cab-user-prefs+xml": [], - "application/vnd.oma.dcd": [], - "application/vnd.oma.dcdc": [], - "application/vnd.oma.dd2+xml": [ - "dd2" - ], - "application/vnd.oma.drm.risd+xml": [], - "application/vnd.oma.group-usage-list+xml": [], - "application/vnd.oma.pal+xml": [], - "application/vnd.oma.poc.detailed-progress-report+xml": [], - "application/vnd.oma.poc.final-report+xml": [], - "application/vnd.oma.poc.groups+xml": [], - "application/vnd.oma.poc.invocation-descriptor+xml": [], - "application/vnd.oma.poc.optimized-progress-report+xml": [], - "application/vnd.oma.push": [], - "application/vnd.oma.scidm.messages+xml": [], - "application/vnd.oma.xcap-directory+xml": [], - "application/vnd.omads-email+xml": [], - "application/vnd.omads-file+xml": [], - "application/vnd.omads-folder+xml": [], - "application/vnd.omaloc-supl-init": [], - "application/vnd.openofficeorg.extension": [ - "oxt" - ], - "application/vnd.openxmlformats-officedocument.custom-properties+xml": [], - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": [], - "application/vnd.openxmlformats-officedocument.drawing+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": [], - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": [], - "application/vnd.openxmlformats-officedocument.extended-properties+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.presentation": [ - "pptx" - ], - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.slide": [ - "sldx" - ], - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": [ - "ppsx" - ], - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.template": [ - "potx" - ], - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": [], - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [ - "xlsx" - ], - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": [ - "xltx" - ], - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": [], - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": [], - "application/vnd.openxmlformats-officedocument.theme+xml": [], - "application/vnd.openxmlformats-officedocument.themeoverride+xml": [], - "application/vnd.openxmlformats-officedocument.vmldrawing": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [ - "docx" - ], - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": [ - "dotx" - ], - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": [], - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": [], - "application/vnd.openxmlformats-package.core-properties+xml": [], - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": [], - "application/vnd.openxmlformats-package.relationships+xml": [], - "application/vnd.quobject-quoxdocument": [], - "application/vnd.osa.netdeploy": [], - "application/vnd.osgeo.mapguide.package": [ - "mgp" - ], - "application/vnd.osgi.bundle": [], - "application/vnd.osgi.dp": [ - "dp" - ], - "application/vnd.osgi.subsystem": [ - "esa" - ], - "application/vnd.otps.ct-kip+xml": [], - "application/vnd.palm": [ - "pdb", - "pqa", - "oprc" - ], - "application/vnd.paos.xml": [], - "application/vnd.pawaafile": [ - "paw" - ], - "application/vnd.pg.format": [ - "str" - ], - "application/vnd.pg.osasli": [ - "ei6" - ], - "application/vnd.piaccess.application-licence": [], - "application/vnd.picsel": [ - "efif" - ], - "application/vnd.pmi.widget": [ - "wg" - ], - "application/vnd.poc.group-advertisement+xml": [], - "application/vnd.pocketlearn": [ - "plf" - ], - "application/vnd.powerbuilder6": [ - "pbd" - ], - "application/vnd.powerbuilder6-s": [], - "application/vnd.powerbuilder7": [], - "application/vnd.powerbuilder7-s": [], - "application/vnd.powerbuilder75": [], - "application/vnd.powerbuilder75-s": [], - "application/vnd.preminet": [], - "application/vnd.previewsystems.box": [ - "box" - ], - "application/vnd.proteus.magazine": [ - "mgz" - ], - "application/vnd.publishare-delta-tree": [ - "qps" - ], - "application/vnd.pvi.ptid1": [ - "ptid" - ], - "application/vnd.pwg-multiplexed": [], - "application/vnd.pwg-xhtml-print+xml": [], - "application/vnd.qualcomm.brew-app-res": [], - "application/vnd.quark.quarkxpress": [ - "qxd", - "qxt", - "qwd", - "qwt", - "qxl", - "qxb" - ], - "application/vnd.radisys.moml+xml": [], - "application/vnd.radisys.msml+xml": [], - "application/vnd.radisys.msml-audit+xml": [], - "application/vnd.radisys.msml-audit-conf+xml": [], - "application/vnd.radisys.msml-audit-conn+xml": [], - "application/vnd.radisys.msml-audit-dialog+xml": [], - "application/vnd.radisys.msml-audit-stream+xml": [], - "application/vnd.radisys.msml-conf+xml": [], - "application/vnd.radisys.msml-dialog+xml": [], - "application/vnd.radisys.msml-dialog-base+xml": [], - "application/vnd.radisys.msml-dialog-fax-detect+xml": [], - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": [], - "application/vnd.radisys.msml-dialog-group+xml": [], - "application/vnd.radisys.msml-dialog-speech+xml": [], - "application/vnd.radisys.msml-dialog-transform+xml": [], - "application/vnd.rainstor.data": [], - "application/vnd.rapid": [], - "application/vnd.realvnc.bed": [ - "bed" - ], - "application/vnd.recordare.musicxml": [ - "mxl" - ], - "application/vnd.recordare.musicxml+xml": [ - "musicxml" - ], - "application/vnd.renlearn.rlprint": [], - "application/vnd.rig.cryptonote": [ - "cryptonote" - ], - "application/vnd.rim.cod": [ - "cod" - ], - "application/vnd.rn-realmedia": [ - "rm" - ], - "application/vnd.rn-realmedia-vbr": [ - "rmvb" - ], - "application/vnd.route66.link66+xml": [ - "link66" - ], - "application/vnd.rs-274x": [], - "application/vnd.ruckus.download": [], - "application/vnd.s3sms": [], - "application/vnd.sailingtracker.track": [ - "st" - ], - "application/vnd.sbm.cid": [], - "application/vnd.sbm.mid2": [], - "application/vnd.scribus": [], - "application/vnd.sealed.3df": [], - "application/vnd.sealed.csf": [], - "application/vnd.sealed.doc": [], - "application/vnd.sealed.eml": [], - "application/vnd.sealed.mht": [], - "application/vnd.sealed.net": [], - "application/vnd.sealed.ppt": [], - "application/vnd.sealed.tiff": [], - "application/vnd.sealed.xls": [], - "application/vnd.sealedmedia.softseal.html": [], - "application/vnd.sealedmedia.softseal.pdf": [], - "application/vnd.seemail": [ - "see" - ], - "application/vnd.sema": [ - "sema" - ], - "application/vnd.semd": [ - "semd" - ], - "application/vnd.semf": [ - "semf" - ], - "application/vnd.shana.informed.formdata": [ - "ifm" - ], - "application/vnd.shana.informed.formtemplate": [ - "itp" - ], - "application/vnd.shana.informed.interchange": [ - "iif" - ], - "application/vnd.shana.informed.package": [ - "ipk" - ], - "application/vnd.simtech-mindmapper": [ - "twd", - "twds" - ], - "application/vnd.smaf": [ - "mmf" - ], - "application/vnd.smart.notebook": [], - "application/vnd.smart.teacher": [ - "teacher" - ], - "application/vnd.software602.filler.form+xml": [], - "application/vnd.software602.filler.form-xml-zip": [], - "application/vnd.solent.sdkm+xml": [ - "sdkm", - "sdkd" - ], - "application/vnd.spotfire.dxp": [ - "dxp" - ], - "application/vnd.spotfire.sfs": [ - "sfs" - ], - "application/vnd.sss-cod": [], - "application/vnd.sss-dtf": [], - "application/vnd.sss-ntf": [], - "application/vnd.stardivision.calc": [ - "sdc" - ], - "application/vnd.stardivision.draw": [ - "sda" - ], - "application/vnd.stardivision.impress": [ - "sdd" - ], - "application/vnd.stardivision.math": [ - "smf" - ], - "application/vnd.stardivision.writer": [ - "sdw", - "vor" - ], - "application/vnd.stardivision.writer-global": [ - "sgl" - ], - "application/vnd.stepmania.package": [ - "smzip" - ], - "application/vnd.stepmania.stepchart": [ - "sm" - ], - "application/vnd.street-stream": [], - "application/vnd.sun.xml.calc": [ - "sxc" - ], - "application/vnd.sun.xml.calc.template": [ - "stc" - ], - "application/vnd.sun.xml.draw": [ - "sxd" - ], - "application/vnd.sun.xml.draw.template": [ - "std" - ], - "application/vnd.sun.xml.impress": [ - "sxi" - ], - "application/vnd.sun.xml.impress.template": [ - "sti" - ], - "application/vnd.sun.xml.math": [ - "sxm" - ], - "application/vnd.sun.xml.writer": [ - "sxw" - ], - "application/vnd.sun.xml.writer.global": [ - "sxg" - ], - "application/vnd.sun.xml.writer.template": [ - "stw" - ], - "application/vnd.sun.wadl+xml": [], - "application/vnd.sus-calendar": [ - "sus", - "susp" - ], - "application/vnd.svd": [ - "svd" - ], - "application/vnd.swiftview-ics": [], - "application/vnd.symbian.install": [ - "sis", - "sisx" - ], - "application/vnd.syncml+xml": [ - "xsm" - ], - "application/vnd.syncml.dm+wbxml": [ - "bdm" - ], - "application/vnd.syncml.dm+xml": [ - "xdm" - ], - "application/vnd.syncml.dm.notification": [], - "application/vnd.syncml.ds.notification": [], - "application/vnd.tao.intent-module-archive": [ - "tao" - ], - "application/vnd.tcpdump.pcap": [ - "pcap", - "cap", - "dmp" - ], - "application/vnd.tmobile-livetv": [ - "tmo" - ], - "application/vnd.trid.tpt": [ - "tpt" - ], - "application/vnd.triscape.mxs": [ - "mxs" - ], - "application/vnd.trueapp": [ - "tra" - ], - "application/vnd.truedoc": [], - "application/vnd.ubisoft.webplayer": [], - "application/vnd.ufdl": [ - "ufd", - "ufdl" - ], - "application/vnd.uiq.theme": [ - "utz" - ], - "application/vnd.umajin": [ - "umj" - ], - "application/vnd.unity": [ - "unityweb" - ], - "application/vnd.uoml+xml": [ - "uoml" - ], - "application/vnd.uplanet.alert": [], - "application/vnd.uplanet.alert-wbxml": [], - "application/vnd.uplanet.bearer-choice": [], - "application/vnd.uplanet.bearer-choice-wbxml": [], - "application/vnd.uplanet.cacheop": [], - "application/vnd.uplanet.cacheop-wbxml": [], - "application/vnd.uplanet.channel": [], - "application/vnd.uplanet.channel-wbxml": [], - "application/vnd.uplanet.list": [], - "application/vnd.uplanet.list-wbxml": [], - "application/vnd.uplanet.listcmd": [], - "application/vnd.uplanet.listcmd-wbxml": [], - "application/vnd.uplanet.signal": [], - "application/vnd.vcx": [ - "vcx" - ], - "application/vnd.vd-study": [], - "application/vnd.vectorworks": [], - "application/vnd.verimatrix.vcas": [], - "application/vnd.vidsoft.vidconference": [], - "application/vnd.visio": [ - "vsd", - "vst", - "vss", - "vsw" - ], - "application/vnd.visionary": [ - "vis" - ], - "application/vnd.vividence.scriptfile": [], - "application/vnd.vsf": [ - "vsf" - ], - "application/vnd.wap.sic": [], - "application/vnd.wap.slc": [], - "application/vnd.wap.wbxml": [ - "wbxml" - ], - "application/vnd.wap.wmlc": [ - "wmlc" - ], - "application/vnd.wap.wmlscriptc": [ - "wmlsc" - ], - "application/vnd.webturbo": [ - "wtb" - ], - "application/vnd.wfa.wsc": [], - "application/vnd.wmc": [], - "application/vnd.wmf.bootstrap": [], - "application/vnd.wolfram.mathematica": [], - "application/vnd.wolfram.mathematica.package": [], - "application/vnd.wolfram.player": [ - "nbp" - ], - "application/vnd.wordperfect": [ - "wpd" - ], - "application/vnd.wqd": [ - "wqd" - ], - "application/vnd.wrq-hp3000-labelled": [], - "application/vnd.wt.stf": [ - "stf" - ], - "application/vnd.wv.csp+wbxml": [], - "application/vnd.wv.csp+xml": [], - "application/vnd.wv.ssp+xml": [], - "application/vnd.xara": [ - "xar" - ], - "application/vnd.xfdl": [ - "xfdl" - ], - "application/vnd.xfdl.webform": [], - "application/vnd.xmi+xml": [], - "application/vnd.xmpie.cpkg": [], - "application/vnd.xmpie.dpkg": [], - "application/vnd.xmpie.plan": [], - "application/vnd.xmpie.ppkg": [], - "application/vnd.xmpie.xlim": [], - "application/vnd.yamaha.hv-dic": [ - "hvd" - ], - "application/vnd.yamaha.hv-script": [ - "hvs" - ], - "application/vnd.yamaha.hv-voice": [ - "hvp" - ], - "application/vnd.yamaha.openscoreformat": [ - "osf" - ], - "application/vnd.yamaha.openscoreformat.osfpvg+xml": [ - "osfpvg" - ], - "application/vnd.yamaha.remote-setup": [], - "application/vnd.yamaha.smaf-audio": [ - "saf" - ], - "application/vnd.yamaha.smaf-phrase": [ - "spf" - ], - "application/vnd.yamaha.through-ngn": [], - "application/vnd.yamaha.tunnel-udpencap": [], - "application/vnd.yellowriver-custom-menu": [ - "cmp" - ], - "application/vnd.zul": [ - "zir", - "zirz" - ], - "application/vnd.zzazz.deck+xml": [ - "zaz" - ], - "application/voicexml+xml": [ - "vxml" - ], - "application/vq-rtcpxr": [], - "application/watcherinfo+xml": [], - "application/whoispp-query": [], - "application/whoispp-response": [], - "application/widget": [ - "wgt" - ], - "application/winhlp": [ - "hlp" - ], - "application/wita": [], - "application/wordperfect5.1": [], - "application/wsdl+xml": [ - "wsdl" - ], - "application/wspolicy+xml": [ - "wspolicy" - ], - "application/x-7z-compressed": [ - "7z" - ], - "application/x-abiword": [ - "abw" - ], - "application/x-ace-compressed": [ - "ace" - ], - "application/x-amf": [], - "application/x-apple-diskimage": [ - "dmg" - ], - "application/x-authorware-bin": [ - "aab", - "x32", - "u32", - "vox" - ], - "application/x-authorware-map": [ - "aam" - ], - "application/x-authorware-seg": [ - "aas" - ], - "application/x-bcpio": [ - "bcpio" - ], - "application/x-bittorrent": [ - "torrent" - ], - "application/x-blorb": [ - "blb", - "blorb" - ], - "application/x-bzip": [ - "bz" - ], - "application/x-bzip2": [ - "bz2", - "boz" - ], - "application/x-cbr": [ - "cbr", - "cba", - "cbt", - "cbz", - "cb7" - ], - "application/x-cdlink": [ - "vcd" - ], - "application/x-cfs-compressed": [ - "cfs" - ], - "application/x-chat": [ - "chat" - ], - "application/x-chess-pgn": [ - "pgn" - ], - "application/x-conference": [ - "nsc" - ], - "application/x-compress": [], - "application/x-cpio": [ - "cpio" - ], - "application/x-csh": [ - "csh" - ], - "application/x-debian-package": [ - "deb", - "udeb" - ], - "application/x-dgc-compressed": [ - "dgc" - ], - "application/x-director": [ - "dir", - "dcr", - "dxr", - "cst", - "cct", - "cxt", - "w3d", - "fgd", - "swa" - ], - "application/x-doom": [ - "wad" - ], - "application/x-dtbncx+xml": [ - "ncx" - ], - "application/x-dtbook+xml": [ - "dtb" - ], - "application/x-dtbresource+xml": [ - "res" - ], - "application/x-dvi": [ - "dvi" - ], - "application/x-envoy": [ - "evy" - ], - "application/x-eva": [ - "eva" - ], - "application/x-font-bdf": [ - "bdf" - ], - "application/x-font-dos": [], - "application/x-font-framemaker": [], - "application/x-font-ghostscript": [ - "gsf" - ], - "application/x-font-libgrx": [], - "application/x-font-linux-psf": [ - "psf" - ], - "application/x-font-otf": [ - "otf" - ], - "application/x-font-pcf": [ - "pcf" - ], - "application/x-font-snf": [ - "snf" - ], - "application/x-font-speedo": [], - "application/x-font-sunos-news": [], - "application/x-font-ttf": [ - "ttf", - "ttc" - ], - "application/x-font-type1": [ - "pfa", - "pfb", - "pfm", - "afm" - ], - "application/font-woff": [ - "woff" - ], - "application/x-font-vfont": [], - "application/x-freearc": [ - "arc" - ], - "application/x-futuresplash": [ - "spl" - ], - "application/x-gca-compressed": [ - "gca" - ], - "application/x-glulx": [ - "ulx" - ], - "application/x-gnumeric": [ - "gnumeric" - ], - "application/x-gramps-xml": [ - "gramps" - ], - "application/x-gtar": [ - "gtar" - ], - "application/x-gzip": [], - "application/x-hdf": [ - "hdf" - ], - "application/x-install-instructions": [ - "install" - ], - "application/x-iso9660-image": [ - "iso" - ], - "application/x-java-jnlp-file": [ - "jnlp" - ], - "application/x-latex": [ - "latex" - ], - "application/x-lzh-compressed": [ - "lzh", - "lha" - ], - "application/x-mie": [ - "mie" - ], - "application/x-mobipocket-ebook": [ - "prc", - "mobi" - ], - "application/x-ms-application": [ - "application" - ], - "application/x-ms-shortcut": [ - "lnk" - ], - "application/x-ms-wmd": [ - "wmd" - ], - "application/x-ms-wmz": [ - "wmz" - ], - "application/x-ms-xbap": [ - "xbap" - ], - "application/x-msaccess": [ - "mdb" - ], - "application/x-msbinder": [ - "obd" - ], - "application/x-mscardfile": [ - "crd" - ], - "application/x-msclip": [ - "clp" - ], - "application/x-msdownload": [ - "exe", - "dll", - "com", - "bat", - "msi" - ], - "application/x-msmediaview": [ - "mvb", - "m13", - "m14" - ], - "application/x-msmetafile": [ - "wmf", - "wmz", - "emf", - "emz" - ], - "application/x-msmoney": [ - "mny" - ], - "application/x-mspublisher": [ - "pub" - ], - "application/x-msschedule": [ - "scd" - ], - "application/x-msterminal": [ - "trm" - ], - "application/x-mswrite": [ - "wri" - ], - "application/x-netcdf": [ - "nc", - "cdf" - ], - "application/x-nzb": [ - "nzb" - ], - "application/x-pkcs12": [ - "p12", - "pfx" - ], - "application/x-pkcs7-certificates": [ - "p7b", - "spc" - ], - "application/x-pkcs7-certreqresp": [ - "p7r" - ], - "application/x-rar-compressed": [ - "rar" - ], - "application/x-research-info-systems": [ - "ris" - ], - "application/x-sh": [ - "sh" - ], - "application/x-shar": [ - "shar" - ], - "application/x-shockwave-flash": [ - "swf" - ], - "application/x-silverlight-app": [ - "xap" - ], - "application/x-sql": [ - "sql" - ], - "application/x-stuffit": [ - "sit" - ], - "application/x-stuffitx": [ - "sitx" - ], - "application/x-subrip": [ - "srt" - ], - "application/x-sv4cpio": [ - "sv4cpio" - ], - "application/x-sv4crc": [ - "sv4crc" - ], - "application/x-t3vm-image": [ - "t3" - ], - "application/x-tads": [ - "gam" - ], - "application/x-tar": [ - "tar" - ], - "application/x-tcl": [ - "tcl" - ], - "application/x-tex": [ - "tex" - ], - "application/x-tex-tfm": [ - "tfm" - ], - "application/x-texinfo": [ - "texinfo", - "texi" - ], - "application/x-tgif": [ - "obj" - ], - "application/x-ustar": [ - "ustar" - ], - "application/x-wais-source": [ - "src" - ], - "application/x-x509-ca-cert": [ - "der", - "crt" - ], - "application/x-xfig": [ - "fig" - ], - "application/x-xliff+xml": [ - "xlf" - ], - "application/x-xpinstall": [ - "xpi" - ], - "application/x-xz": [ - "xz" - ], - "application/x-zmachine": [ - "z1", - "z2", - "z3", - "z4", - "z5", - "z6", - "z7", - "z8" - ], - "application/x400-bp": [], - "application/xaml+xml": [ - "xaml" - ], - "application/xcap-att+xml": [], - "application/xcap-caps+xml": [], - "application/xcap-diff+xml": [ - "xdf" - ], - "application/xcap-el+xml": [], - "application/xcap-error+xml": [], - "application/xcap-ns+xml": [], - "application/xcon-conference-info-diff+xml": [], - "application/xcon-conference-info+xml": [], - "application/xenc+xml": [ - "xenc" - ], - "application/xhtml+xml": [ - "xhtml", - "xht" - ], - "application/xhtml-voice+xml": [], - "application/xml": [ - "xml", - "xsl" - ], - "application/xml-dtd": [ - "dtd" - ], - "application/xml-external-parsed-entity": [], - "application/xmpp+xml": [], - "application/xop+xml": [ - "xop" - ], - "application/xproc+xml": [ - "xpl" - ], - "application/xslt+xml": [ - "xslt" - ], - "application/xspf+xml": [ - "xspf" - ], - "application/xv+xml": [ - "mxml", - "xhvml", - "xvml", - "xvm" - ], - "application/yang": [ - "yang" - ], - "application/yin+xml": [ - "yin" - ], - "application/zip": [ - "zip" - ], - "audio/1d-interleaved-parityfec": [], - "audio/32kadpcm": [], - "audio/3gpp": [], - "audio/3gpp2": [], - "audio/ac3": [], - "audio/adpcm": [ - "adp" - ], - "audio/amr": [], - "audio/amr-wb": [], - "audio/amr-wb+": [], - "audio/asc": [], - "audio/atrac-advanced-lossless": [], - "audio/atrac-x": [], - "audio/atrac3": [], - "audio/basic": [ - "au", - "snd" - ], - "audio/bv16": [], - "audio/bv32": [], - "audio/clearmode": [], - "audio/cn": [], - "audio/dat12": [], - "audio/dls": [], - "audio/dsr-es201108": [], - "audio/dsr-es202050": [], - "audio/dsr-es202211": [], - "audio/dsr-es202212": [], - "audio/dv": [], - "audio/dvi4": [], - "audio/eac3": [], - "audio/evrc": [], - "audio/evrc-qcp": [], - "audio/evrc0": [], - "audio/evrc1": [], - "audio/evrcb": [], - "audio/evrcb0": [], - "audio/evrcb1": [], - "audio/evrcwb": [], - "audio/evrcwb0": [], - "audio/evrcwb1": [], - "audio/example": [], - "audio/fwdred": [], - "audio/g719": [], - "audio/g722": [], - "audio/g7221": [], - "audio/g723": [], - "audio/g726-16": [], - "audio/g726-24": [], - "audio/g726-32": [], - "audio/g726-40": [], - "audio/g728": [], - "audio/g729": [], - "audio/g7291": [], - "audio/g729d": [], - "audio/g729e": [], - "audio/gsm": [], - "audio/gsm-efr": [], - "audio/gsm-hr-08": [], - "audio/ilbc": [], - "audio/ip-mr_v2.5": [], - "audio/isac": [], - "audio/l16": [], - "audio/l20": [], - "audio/l24": [], - "audio/l8": [], - "audio/lpc": [], - "audio/midi": [ - "mid", - "midi", - "kar", - "rmi" - ], - "audio/mobile-xmf": [], - "audio/mp4": [ - "mp4a" - ], - "audio/mp4a-latm": [], - "audio/mpa": [], - "audio/mpa-robust": [], - "audio/mpeg": [ - "mpga", - "mp2", - "mp2a", - "mp3", - "m2a", - "m3a" - ], - "audio/mpeg4-generic": [], - "audio/musepack": [], - "audio/ogg": [ - "oga", - "ogg", - "spx" - ], - "audio/opus": [], - "audio/parityfec": [], - "audio/pcma": [], - "audio/pcma-wb": [], - "audio/pcmu-wb": [], - "audio/pcmu": [], - "audio/prs.sid": [], - "audio/qcelp": [], - "audio/red": [], - "audio/rtp-enc-aescm128": [], - "audio/rtp-midi": [], - "audio/rtx": [], - "audio/s3m": [ - "s3m" - ], - "audio/silk": [ - "sil" - ], - "audio/smv": [], - "audio/smv0": [], - "audio/smv-qcp": [], - "audio/sp-midi": [], - "audio/speex": [], - "audio/t140c": [], - "audio/t38": [], - "audio/telephone-event": [], - "audio/tone": [], - "audio/uemclip": [], - "audio/ulpfec": [], - "audio/vdvi": [], - "audio/vmr-wb": [], - "audio/vnd.3gpp.iufp": [], - "audio/vnd.4sb": [], - "audio/vnd.audiokoz": [], - "audio/vnd.celp": [], - "audio/vnd.cisco.nse": [], - "audio/vnd.cmles.radio-events": [], - "audio/vnd.cns.anp1": [], - "audio/vnd.cns.inf1": [], - "audio/vnd.dece.audio": [ - "uva", - "uvva" - ], - "audio/vnd.digital-winds": [ - "eol" - ], - "audio/vnd.dlna.adts": [], - "audio/vnd.dolby.heaac.1": [], - "audio/vnd.dolby.heaac.2": [], - "audio/vnd.dolby.mlp": [], - "audio/vnd.dolby.mps": [], - "audio/vnd.dolby.pl2": [], - "audio/vnd.dolby.pl2x": [], - "audio/vnd.dolby.pl2z": [], - "audio/vnd.dolby.pulse.1": [], - "audio/vnd.dra": [ - "dra" - ], - "audio/vnd.dts": [ - "dts" - ], - "audio/vnd.dts.hd": [ - "dtshd" - ], - "audio/vnd.dvb.file": [], - "audio/vnd.everad.plj": [], - "audio/vnd.hns.audio": [], - "audio/vnd.lucent.voice": [ - "lvp" - ], - "audio/vnd.ms-playready.media.pya": [ - "pya" - ], - "audio/vnd.nokia.mobile-xmf": [], - "audio/vnd.nortel.vbk": [], - "audio/vnd.nuera.ecelp4800": [ - "ecelp4800" - ], - "audio/vnd.nuera.ecelp7470": [ - "ecelp7470" - ], - "audio/vnd.nuera.ecelp9600": [ - "ecelp9600" - ], - "audio/vnd.octel.sbc": [], - "audio/vnd.qcelp": [], - "audio/vnd.rhetorex.32kadpcm": [], - "audio/vnd.rip": [ - "rip" - ], - "audio/vnd.sealedmedia.softseal.mpeg": [], - "audio/vnd.vmx.cvsd": [], - "audio/vorbis": [], - "audio/vorbis-config": [], - "audio/webm": [ - "weba" - ], - "audio/x-aac": [ - "aac" - ], - "audio/x-aiff": [ - "aif", - "aiff", - "aifc" - ], - "audio/x-caf": [ - "caf" - ], - "audio/x-flac": [ - "flac" - ], - "audio/x-matroska": [ - "mka" - ], - "audio/x-mpegurl": [ - "m3u" - ], - "audio/x-ms-wax": [ - "wax" - ], - "audio/x-ms-wma": [ - "wma" - ], - "audio/x-pn-realaudio": [ - "ram", - "ra" - ], - "audio/x-pn-realaudio-plugin": [ - "rmp" - ], - "audio/x-tta": [], - "audio/x-wav": [ - "wav" - ], - "audio/xm": [ - "xm" - ], - "chemical/x-cdx": [ - "cdx" - ], - "chemical/x-cif": [ - "cif" - ], - "chemical/x-cmdf": [ - "cmdf" - ], - "chemical/x-cml": [ - "cml" - ], - "chemical/x-csml": [ - "csml" - ], - "chemical/x-pdb": [], - "chemical/x-xyz": [ - "xyz" - ], - "image/bmp": [ - "bmp" - ], - "image/cgm": [ - "cgm" - ], - "image/example": [], - "image/fits": [], - "image/g3fax": [ - "g3" - ], - "image/gif": [ - "gif" - ], - "image/ief": [ - "ief" - ], - "image/jp2": [], - "image/jpeg": [ - "jpeg", - "jpg", - "jpe" - ], - "image/jpm": [], - "image/jpx": [], - "image/ktx": [ - "ktx" - ], - "image/naplps": [], - "image/png": [ - "png" - ], - "image/prs.btif": [ - "btif" - ], - "image/prs.pti": [], - "image/sgi": [ - "sgi" - ], - "image/svg+xml": [ - "svg", - "svgz" - ], - "image/t38": [], - "image/tiff": [ - "tiff", - "tif" - ], - "image/tiff-fx": [], - "image/vnd.adobe.photoshop": [ - "psd" - ], - "image/vnd.cns.inf2": [], - "image/vnd.dece.graphic": [ - "uvi", - "uvvi", - "uvg", - "uvvg" - ], - "image/vnd.dvb.subtitle": [ - "sub" - ], - "image/vnd.djvu": [ - "djvu", - "djv" - ], - "image/vnd.dwg": [ - "dwg" - ], - "image/vnd.dxf": [ - "dxf" - ], - "image/vnd.fastbidsheet": [ - "fbs" - ], - "image/vnd.fpx": [ - "fpx" - ], - "image/vnd.fst": [ - "fst" - ], - "image/vnd.fujixerox.edmics-mmr": [ - "mmr" - ], - "image/vnd.fujixerox.edmics-rlc": [ - "rlc" - ], - "image/vnd.globalgraphics.pgb": [], - "image/vnd.microsoft.icon": [], - "image/vnd.mix": [], - "image/vnd.ms-modi": [ - "mdi" - ], - "image/vnd.ms-photo": [ - "wdp" - ], - "image/vnd.net-fpx": [ - "npx" - ], - "image/vnd.radiance": [], - "image/vnd.sealed.png": [], - "image/vnd.sealedmedia.softseal.gif": [], - "image/vnd.sealedmedia.softseal.jpg": [], - "image/vnd.svf": [], - "image/vnd.wap.wbmp": [ - "wbmp" - ], - "image/vnd.xiff": [ - "xif" - ], - "image/webp": [ - "webp" - ], - "image/x-3ds": [ - "3ds" - ], - "image/x-cmu-raster": [ - "ras" - ], - "image/x-cmx": [ - "cmx" - ], - "image/x-freehand": [ - "fh", - "fhc", - "fh4", - "fh5", - "fh7" - ], - "image/x-icon": [ - "ico" - ], - "image/x-mrsid-image": [ - "sid" - ], - "image/x-pcx": [ - "pcx" - ], - "image/x-pict": [ - "pic", - "pct" - ], - "image/x-portable-anymap": [ - "pnm" - ], - "image/x-portable-bitmap": [ - "pbm" - ], - "image/x-portable-graymap": [ - "pgm" - ], - "image/x-portable-pixmap": [ - "ppm" - ], - "image/x-rgb": [ - "rgb" - ], - "image/x-tga": [ - "tga" - ], - "image/x-xbitmap": [ - "xbm" - ], - "image/x-xpixmap": [ - "xpm" - ], - "image/x-xwindowdump": [ - "xwd" - ], - "message/cpim": [], - "message/delivery-status": [], - "message/disposition-notification": [], - "message/example": [], - "message/external-body": [], - "message/feedback-report": [], - "message/global": [], - "message/global-delivery-status": [], - "message/global-disposition-notification": [], - "message/global-headers": [], - "message/http": [], - "message/imdn+xml": [], - "message/news": [], - "message/partial": [], - "message/rfc822": [ - "eml", - "mime" - ], - "message/s-http": [], - "message/sip": [], - "message/sipfrag": [], - "message/tracking-status": [], - "message/vnd.si.simp": [], - "model/example": [], - "model/iges": [ - "igs", - "iges" - ], - "model/mesh": [ - "msh", - "mesh", - "silo" - ], - "model/vnd.collada+xml": [ - "dae" - ], - "model/vnd.dwf": [ - "dwf" - ], - "model/vnd.flatland.3dml": [], - "model/vnd.gdl": [ - "gdl" - ], - "model/vnd.gs-gdl": [], - "model/vnd.gs.gdl": [], - "model/vnd.gtw": [ - "gtw" - ], - "model/vnd.moml+xml": [], - "model/vnd.mts": [ - "mts" - ], - "model/vnd.parasolid.transmit.binary": [], - "model/vnd.parasolid.transmit.text": [], - "model/vnd.vtu": [ - "vtu" - ], - "model/vrml": [ - "wrl", - "vrml" - ], - "model/x3d+binary": [ - "x3db", - "x3dbz" - ], - "model/x3d+vrml": [ - "x3dv", - "x3dvz" - ], - "model/x3d+xml": [ - "x3d", - "x3dz" - ], - "multipart/alternative": [], - "multipart/appledouble": [], - "multipart/byteranges": [], - "multipart/digest": [], - "multipart/encrypted": [], - "multipart/example": [], - "multipart/form-data": [], - "multipart/header-set": [], - "multipart/mixed": [], - "multipart/parallel": [], - "multipart/related": [], - "multipart/report": [], - "multipart/signed": [], - "multipart/voice-message": [], - "text/1d-interleaved-parityfec": [], - "text/cache-manifest": [ - "appcache" - ], - "text/calendar": [ - "ics", - "ifb" - ], - "text/css": [ - "css" - ], - "text/csv": [ - "csv" - ], - "text/directory": [], - "text/dns": [], - "text/ecmascript": [], - "text/enriched": [], - "text/example": [], - "text/fwdred": [], - "text/html": [ - "html", - "htm" - ], - "text/javascript": [], - "text/n3": [ - "n3" - ], - "text/parityfec": [], - "text/plain": [ - "txt", - "text", - "conf", - "def", - "list", - "log", - "in" - ], - "text/prs.fallenstein.rst": [], - "text/prs.lines.tag": [ - "dsc" - ], - "text/vnd.radisys.msml-basic-layout": [], - "text/red": [], - "text/rfc822-headers": [], - "text/richtext": [ - "rtx" - ], - "text/rtf": [], - "text/rtp-enc-aescm128": [], - "text/rtx": [], - "text/sgml": [ - "sgml", - "sgm" - ], - "text/t140": [], - "text/tab-separated-values": [ - "tsv" - ], - "text/troff": [ - "t", - "tr", - "roff", - "man", - "me", - "ms" - ], - "text/turtle": [ - "ttl" - ], - "text/ulpfec": [], - "text/uri-list": [ - "uri", - "uris", - "urls" - ], - "text/vcard": [ - "vcard" - ], - "text/vnd.abc": [], - "text/vnd.curl": [ - "curl" - ], - "text/vnd.curl.dcurl": [ - "dcurl" - ], - "text/vnd.curl.scurl": [ - "scurl" - ], - "text/vnd.curl.mcurl": [ - "mcurl" - ], - "text/vnd.dmclientscript": [], - "text/vnd.dvb.subtitle": [ - "sub" - ], - "text/vnd.esmertec.theme-descriptor": [], - "text/vnd.fly": [ - "fly" - ], - "text/vnd.fmi.flexstor": [ - "flx" - ], - "text/vnd.graphviz": [ - "gv" - ], - "text/vnd.in3d.3dml": [ - "3dml" - ], - "text/vnd.in3d.spot": [ - "spot" - ], - "text/vnd.iptc.newsml": [], - "text/vnd.iptc.nitf": [], - "text/vnd.latex-z": [], - "text/vnd.motorola.reflex": [], - "text/vnd.ms-mediapackage": [], - "text/vnd.net2phone.commcenter.command": [], - "text/vnd.si.uricatalogue": [], - "text/vnd.sun.j2me.app-descriptor": [ - "jad" - ], - "text/vnd.trolltech.linguist": [], - "text/vnd.wap.si": [], - "text/vnd.wap.sl": [], - "text/vnd.wap.wml": [ - "wml" - ], - "text/vnd.wap.wmlscript": [ - "wmls" - ], - "text/x-asm": [ - "s", - "asm" - ], - "text/x-c": [ - "c", - "cc", - "cxx", - "cpp", - "h", - "hh", - "dic" - ], - "text/x-fortran": [ - "f", - "for", - "f77", - "f90" - ], - "text/x-java-source": [ - "java" - ], - "text/x-opml": [ - "opml" - ], - "text/x-pascal": [ - "p", - "pas" - ], - "text/x-nfo": [ - "nfo" - ], - "text/x-setext": [ - "etx" - ], - "text/x-sfv": [ - "sfv" - ], - "text/x-uuencode": [ - "uu" - ], - "text/x-vcalendar": [ - "vcs" - ], - "text/x-vcard": [ - "vcf" - ], - "text/xml": [], - "text/xml-external-parsed-entity": [], - "video/1d-interleaved-parityfec": [], - "video/3gpp": [ - "3gp" - ], - "video/3gpp-tt": [], - "video/3gpp2": [ - "3g2" - ], - "video/bmpeg": [], - "video/bt656": [], - "video/celb": [], - "video/dv": [], - "video/example": [], - "video/h261": [ - "h261" - ], - "video/h263": [ - "h263" - ], - "video/h263-1998": [], - "video/h263-2000": [], - "video/h264": [ - "h264" - ], - "video/h264-rcdo": [], - "video/h264-svc": [], - "video/jpeg": [ - "jpgv" - ], - "video/jpeg2000": [], - "video/jpm": [ - "jpm", - "jpgm" - ], - "video/mj2": [ - "mj2", - "mjp2" - ], - "video/mp1s": [], - "video/mp2p": [], - "video/mp2t": [], - "video/mp4": [ - "mp4", - "mp4v", - "mpg4" - ], - "video/mp4v-es": [], - "video/mpeg": [ - "mpeg", - "mpg", - "mpe", - "m1v", - "m2v" - ], - "video/mpeg4-generic": [], - "video/mpv": [], - "video/nv": [], - "video/ogg": [ - "ogv" - ], - "video/parityfec": [], - "video/pointer": [], - "video/quicktime": [ - "qt", - "mov" - ], - "video/raw": [], - "video/rtp-enc-aescm128": [], - "video/rtx": [], - "video/smpte292m": [], - "video/ulpfec": [], - "video/vc1": [], - "video/vnd.cctv": [], - "video/vnd.dece.hd": [ - "uvh", - "uvvh" - ], - "video/vnd.dece.mobile": [ - "uvm", - "uvvm" - ], - "video/vnd.dece.mp4": [], - "video/vnd.dece.pd": [ - "uvp", - "uvvp" - ], - "video/vnd.dece.sd": [ - "uvs", - "uvvs" - ], - "video/vnd.dece.video": [ - "uvv", - "uvvv" - ], - "video/vnd.directv.mpeg": [], - "video/vnd.directv.mpeg-tts": [], - "video/vnd.dlna.mpeg-tts": [], - "video/vnd.dvb.file": [ - "dvb" - ], - "video/vnd.fvt": [ - "fvt" - ], - "video/vnd.hns.video": [], - "video/vnd.iptvforum.1dparityfec-1010": [], - "video/vnd.iptvforum.1dparityfec-2005": [], - "video/vnd.iptvforum.2dparityfec-1010": [], - "video/vnd.iptvforum.2dparityfec-2005": [], - "video/vnd.iptvforum.ttsavc": [], - "video/vnd.iptvforum.ttsmpeg2": [], - "video/vnd.motorola.video": [], - "video/vnd.motorola.videop": [], - "video/vnd.mpegurl": [ - "mxu", - "m4u" - ], - "video/vnd.ms-playready.media.pyv": [ - "pyv" - ], - "video/vnd.nokia.interleaved-multimedia": [], - "video/vnd.nokia.videovoip": [], - "video/vnd.objectvideo": [], - "video/vnd.sealed.mpeg1": [], - "video/vnd.sealed.mpeg4": [], - "video/vnd.sealed.swf": [], - "video/vnd.sealedmedia.softseal.mov": [], - "video/vnd.uvvu.mp4": [ - "uvu", - "uvvu" - ], - "video/vnd.vivo": [ - "viv" - ], - "video/webm": [ - "webm" - ], - "video/x-f4v": [ - "f4v" - ], - "video/x-fli": [ - "fli" - ], - "video/x-flv": [ - "flv" - ], - "video/x-m4v": [ - "m4v" - ], - "video/x-matroska": [ - "mkv", - "mk3d", - "mks" - ], - "video/x-mng": [ - "mng" - ], - "video/x-ms-asf": [ - "asf", - "asx" - ], - "video/x-ms-vob": [ - "vob" - ], - "video/x-ms-wm": [ - "wm" - ], - "video/x-ms-wmv": [ - "wmv" - ], - "video/x-ms-wmx": [ - "wmx" - ], - "video/x-ms-wvx": [ - "wvx" - ], - "video/x-msvideo": [ - "avi" - ], - "video/x-sgi-movie": [ - "movie" - ], - "video/x-smv": [ - "smv" - ], - "x-conference/x-cooltalk": [ - "ice" - ] -} diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/node.json b/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/node.json deleted file mode 100644 index ad50d61..0000000 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/lib/node.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "text/vtt": [ - "vtt" - ], - "application/x-chrome-extension": [ - "crx" - ], - "text/x-component": [ - "htc" - ], - "text/cache-manifest": [ - "manifest" - ], - "application/octet-stream": [ - "buffer" - ], - "application/mp4": [ - "m4p" - ], - "audio/mp4": [ - "m4a" - ], - "video/MP2T": [ - "ts" - ], - "application/x-web-app-manifest+json": [ - "webapp" - ], - "text/x-lua": [ - "lua" - ], - "application/x-lua-bytecode": [ - "luac" - ], - "text/x-markdown": [ - "markdown", - "md", - "mkd" - ], - "text/plain": [ - "ini" - ], - "application/dash+xml": [ - "mdp" - ], - "font/opentype": [ - "otf" - ], - "application/json": [ - "map" - ], - "application/xml": [ - "xsd" - ] -} diff --git a/node_modules/express/node_modules/vary/.npmignore b/node_modules/express/node_modules/vary/.npmignore deleted file mode 100644 index cd39b77..0000000 --- a/node_modules/express/node_modules/vary/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -coverage/ -test/ -.travis.yml diff --git a/node_modules/express/package.json b/node_modules/express/package.json index fd1896d..f802220 100644 --- a/node_modules/express/package.json +++ b/node_modules/express/package.json @@ -1,11 +1,36 @@ { - "name": "express", - "description": "Fast, unopinionated, minimalist web framework", - "version": "4.5.1", + "_from": "express@~4.5.1", + "_id": "express@4.5.1", + "_inBundle": false, + "_integrity": "sha1-S8Pm7J2yjldf5ZHDb7t4H/72/nw=", + "_location": "/express", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "express@~4.5.1", + "name": "express", + "escapedName": "express", + "rawSpec": "~4.5.1", + "saveSpec": null, + "fetchSpec": "~4.5.1" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "http://registry.npmjs.org/express/-/express-4.5.1.tgz", + "_shasum": "4bc3e6ec9db28e575fe591c36fbb781ffef6fe7c", + "_spec": "express@~4.5.1", + "_where": "E:\\github\\node-dc-mongo", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, + "bugs": { + "url": "https://github.com/visionmedia/express/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Aaron Heckmann", @@ -31,112 +56,77 @@ "name": "Roman Shtylman" } ], - "keywords": [ - "express", - "framework", - "sinatra", - "web", - "rest", - "restful", - "router", - "app", - "api" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/express" - }, - "license": "MIT", "dependencies": { "accepts": "~1.0.7", "buffer-crc32": "0.2.3", + "cookie": "0.1.2", + "cookie-signature": "1.0.4", "debug": "1.0.2", "depd": "0.3.0", "escape-html": "1.0.1", "finalhandler": "0.0.2", + "fresh": "0.2.2", "media-typer": "0.2.0", + "merge-descriptors": "0.0.2", "methods": "1.0.1", "parseurl": "1.0.1", + "path-to-regexp": "0.1.2", "proxy-addr": "1.0.1", + "qs": "0.6.6", "range-parser": "1.0.0", "send": "0.5.0", "serve-static": "~1.3.0", "type-is": "~1.3.2", - "vary": "0.1.0", - "cookie": "0.1.2", - "fresh": "0.2.2", - "cookie-signature": "1.0.4", - "merge-descriptors": "0.0.2", "utils-merge": "1.0.0", - "qs": "0.6.6", - "path-to-regexp": "0.1.2" + "vary": "0.1.0" }, + "deprecated": false, + "description": "Fast, unopinionated, minimalist web framework", "devDependencies": { "after": "0.8.1", - "istanbul": "0.2.14", - "mocha": "~1.20.1", - "should": "~4.0.4", - "supertest": "~0.13.0", + "body-parser": "~1.4.3", "connect-redis": "~2.0.0", + "cookie-parser": "~1.3.1", "ejs": "~1.0.0", + "express-session": "~1.6.1", + "hjs": "~0.0.6", + "istanbul": "0.2.14", "jade": "~1.3.1", "marked": "0.3.2", - "hjs": "~0.0.6", - "body-parser": "~1.4.3", - "cookie-parser": "~1.3.1", - "express-session": "~1.6.1", "method-override": "2.0.2", - "multiparty": "~3.3.0", + "mocha": "~1.20.1", "morgan": "1.1.1", + "multiparty": "~3.3.0", + "should": "~4.0.4", + "supertest": "~0.13.0", "vhost": "2.0.0" }, "engines": { "node": ">= 0.10.0" }, + "homepage": "https://github.com/visionmedia/express#readme", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "license": "MIT", + "name": "express", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/express.git" + }, "scripts": { "prepublish": "npm prune", "test": "mocha --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/" }, - "bugs": { - "url": "https://github.com/visionmedia/express/issues" - }, - "homepage": "https://github.com/visionmedia/express", - "_id": "express@4.5.1", - "dist": { - "shasum": "4bc3e6ec9db28e575fe591c36fbb781ffef6fe7c", - "tarball": "http://registry.npmjs.org/express/-/express-4.5.1.tgz" - }, - "_from": "express@>=4.5.1 <4.6.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, - { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "aredridel", - "email": "aredridel@nbtsc.org" - } - ], - "directories": {}, - "_shasum": "4bc3e6ec9db28e575fe591c36fbb781ffef6fe7c", - "_resolved": "https://registry.npmjs.org/express/-/express-4.5.1.tgz" + "version": "4.5.1" } diff --git a/node_modules/express/node_modules/finalhandler/.npmignore b/node_modules/finalhandler/.npmignore similarity index 100% rename from node_modules/express/node_modules/finalhandler/.npmignore rename to node_modules/finalhandler/.npmignore diff --git a/node_modules/express/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md similarity index 100% rename from node_modules/express/node_modules/finalhandler/HISTORY.md rename to node_modules/finalhandler/HISTORY.md diff --git a/node_modules/express/node_modules/finalhandler/README.md b/node_modules/finalhandler/README.md similarity index 100% rename from node_modules/express/node_modules/finalhandler/README.md rename to node_modules/finalhandler/README.md diff --git a/node_modules/express/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js similarity index 100% rename from node_modules/express/node_modules/finalhandler/index.js rename to node_modules/finalhandler/index.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/.jshintrc b/node_modules/finalhandler/node_modules/debug/.jshintrc similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/.jshintrc rename to node_modules/finalhandler/node_modules/debug/.jshintrc diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/.npmignore b/node_modules/finalhandler/node_modules/debug/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/.npmignore rename to node_modules/finalhandler/node_modules/debug/.npmignore diff --git a/node_modules/finalhandler/node_modules/debug/History.md b/node_modules/finalhandler/node_modules/debug/History.md new file mode 100644 index 0000000..42139a8 --- /dev/null +++ b/node_modules/finalhandler/node_modules/debug/History.md @@ -0,0 +1,126 @@ + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/Makefile b/node_modules/finalhandler/node_modules/debug/Makefile similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/Makefile rename to node_modules/finalhandler/node_modules/debug/Makefile diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/Readme.md b/node_modules/finalhandler/node_modules/debug/Readme.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/Readme.md rename to node_modules/finalhandler/node_modules/debug/Readme.md diff --git a/node_modules/finalhandler/node_modules/debug/browser.js b/node_modules/finalhandler/node_modules/debug/browser.js new file mode 100644 index 0000000..41d957c --- /dev/null +++ b/node_modules/finalhandler/node_modules/debug/browser.js @@ -0,0 +1,144 @@ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors and the Firebug + * extension (*not* the built-in Firefox web inpector) are + * known to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // is webkit? http://stackoverflow.com/a/16459606/376773 + return ('WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (window.console && (console.firebug || (console.exception && console.table))); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + return JSON.stringify(v); +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? '%c ' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return args + + var c = 'color: ' + this.color; + args = [args[0], c, ''].concat(Array.prototype.slice.call(args, 1)); + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + return args; +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // This hackery is required for IE8, + // where the `console.log` function doesn't have 'apply' + return 'object' == typeof console + && 'function' == typeof console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + localStorage.removeItem('debug'); + } else { + localStorage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = localStorage.debug; + } catch(e) {} + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); diff --git a/node_modules/finalhandler/node_modules/debug/component.json b/node_modules/finalhandler/node_modules/debug/component.json new file mode 100644 index 0000000..dfb0311 --- /dev/null +++ b/node_modules/finalhandler/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "1.0.2", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "guille/ms.js": "0.6.1" + } +} diff --git a/node_modules/finalhandler/node_modules/debug/debug.js b/node_modules/finalhandler/node_modules/debug/debug.js new file mode 100644 index 0000000..c514fb7 --- /dev/null +++ b/node_modules/finalhandler/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lowercased letter, i.e. "n". + */ + +exports.formatters = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function selectColor() { + return exports.colors[prevColor++ % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function debug(namespace) { + + // define the `disabled` version + function disabled() { + } + disabled.enabled = false; + + // define the `enabled` version + function enabled() { + + var self = enabled; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // add the `color` if not set + if (null == self.useColors) self.useColors = exports.useColors(); + if (null == self.color && self.useColors) self.color = selectColor(); + + var args = Array.prototype.slice.call(arguments); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %o + args = ['%o'].concat(args); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + if ('function' === typeof exports.formatArgs) { + args = exports.formatArgs.apply(self, args); + } + var logFn = exports.log || enabled.log || console.log.bind(console); + logFn.apply(self, args); + } + enabled.enabled = true; + + var fn = exports.enabled(namespace) ? enabled : disabled; + + fn.namespace = namespace; + + return fn; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace('*', '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/node.js b/node_modules/finalhandler/node_modules/debug/node.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/node.js rename to node_modules/finalhandler/node_modules/debug/node.js diff --git a/node_modules/finalhandler/node_modules/debug/package.json b/node_modules/finalhandler/node_modules/debug/package.json new file mode 100644 index 0000000..71f7172 --- /dev/null +++ b/node_modules/finalhandler/node_modules/debug/package.json @@ -0,0 +1,69 @@ +{ + "_from": "debug@1.0.2", + "_id": "debug@1.0.2", + "_inBundle": false, + "_integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", + "_location": "/finalhandler/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@1.0.2", + "name": "debug", + "escapedName": "debug", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/finalhandler" + ], + "_resolved": "http://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "_shasum": "3849591c10cce648476c3c7c2e2e3416db5963c4", + "_spec": "debug@1.0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\finalhandler", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "dependencies": { + "ms": "0.6.2" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "4.1.6", + "mocha": "*" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "./node.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "1.0.2" +} diff --git a/node_modules/express/node_modules/send/node_modules/ms/.npmignore b/node_modules/finalhandler/node_modules/ms/.npmignore similarity index 100% rename from node_modules/express/node_modules/send/node_modules/ms/.npmignore rename to node_modules/finalhandler/node_modules/ms/.npmignore diff --git a/node_modules/express/node_modules/send/node_modules/ms/README.md b/node_modules/finalhandler/node_modules/ms/README.md similarity index 100% rename from node_modules/express/node_modules/send/node_modules/ms/README.md rename to node_modules/finalhandler/node_modules/ms/README.md diff --git a/node_modules/express/node_modules/send/node_modules/ms/index.js b/node_modules/finalhandler/node_modules/ms/index.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/ms/index.js rename to node_modules/finalhandler/node_modules/ms/index.js diff --git a/node_modules/finalhandler/node_modules/ms/package.json b/node_modules/finalhandler/node_modules/ms/package.json new file mode 100644 index 0000000..db660ca --- /dev/null +++ b/node_modules/finalhandler/node_modules/ms/package.json @@ -0,0 +1,49 @@ +{ + "_from": "ms@0.6.2", + "_id": "ms@0.6.2", + "_inBundle": false, + "_integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=", + "_location": "/finalhandler/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.6.2", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.6.2", + "saveSpec": null, + "fetchSpec": "0.6.2" + }, + "_requiredBy": [ + "/finalhandler/debug" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", + "_spec": "ms@0.6.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\finalhandler\\node_modules\\debug", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "ms/index.js": "index.js" + } + }, + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" + }, + "homepage": "https://github.com/guille/ms.js#readme", + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git://github.com/guille/ms.js.git" + }, + "version": "0.6.2" +} diff --git a/node_modules/express/node_modules/finalhandler/package.json b/node_modules/finalhandler/package.json similarity index 70% rename from node_modules/express/node_modules/finalhandler/package.json rename to node_modules/finalhandler/package.json index 0c0e9b1..439285f 100644 --- a/node_modules/express/node_modules/finalhandler/package.json +++ b/node_modules/finalhandler/package.json @@ -1,49 +1,62 @@ { - "name": "finalhandler", - "description": "Node.js final http responder", - "version": "0.0.2", + "_from": "finalhandler@0.0.2", + "_id": "finalhandler@0.0.2", + "_inBundle": false, + "_integrity": "sha1-BgPYde6H1WeiZmkoFcyK1E/M7to=", + "_location": "/finalhandler", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "finalhandler@0.0.2", + "name": "finalhandler", + "escapedName": "finalhandler", + "rawSpec": "0.0.2", + "saveSpec": null, + "fetchSpec": "0.0.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz", + "_shasum": "0603d875ee87d567a266692815cc8ad44fcceeda", + "_spec": "finalhandler@0.0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/finalhandler" + "bugs": { + "url": "https://github.com/expressjs/finalhandler/issues" }, + "bundleDependencies": false, "dependencies": { "debug": "1.0.2", "escape-html": "1.0.1" }, + "deprecated": false, + "description": "Node.js final http responder", "devDependencies": { "istanbul": "0.2.10", "mocha": "~1.20.1", "should": "~4.0.1", "supertest": "~0.13.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/finalhandler/issues" - }, - "homepage": "https://github.com/expressjs/finalhandler", - "_id": "finalhandler@0.0.2", + "directories": {}, "dist": { "shasum": "0603d875ee87d567a266692815cc8ad44fcceeda", "tarball": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz" }, - "_from": "finalhandler@0.0.2", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/finalhandler", + "license": "MIT", "maintainers": [ { "name": "dougwilson", @@ -66,7 +79,15 @@ "email": "fishrock123@rocketmail.com" } ], - "directories": {}, - "_shasum": "0603d875ee87d567a266692815cc8ad44fcceeda", - "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz" + "name": "finalhandler", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/finalhandler.git" + }, + "scripts": { + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "version": "0.0.2" } diff --git a/node_modules/express/node_modules/media-typer/.npmignore b/node_modules/finished/.npmignore similarity index 100% rename from node_modules/express/node_modules/media-typer/.npmignore rename to node_modules/finished/.npmignore diff --git a/node_modules/express/node_modules/send/node_modules/finished/HISTORY.md b/node_modules/finished/HISTORY.md similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/HISTORY.md rename to node_modules/finished/HISTORY.md diff --git a/node_modules/express/node_modules/send/node_modules/finished/README.md b/node_modules/finished/README.md similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/README.md rename to node_modules/finished/README.md diff --git a/node_modules/express/node_modules/send/node_modules/finished/index.js b/node_modules/finished/index.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/index.js rename to node_modules/finished/index.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/package.json b/node_modules/finished/package.json similarity index 74% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/package.json rename to node_modules/finished/package.json index b645a74..274d95e 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/package.json +++ b/node_modules/finished/package.json @@ -1,45 +1,62 @@ { - "name": "finished", - "description": "Execute a callback when a request closes, finishes, or errors", - "version": "1.2.2", + "_from": "finished@1.2.2", + "_id": "finished@1.2.2", + "_inBundle": false, + "_integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", + "_location": "/finished", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "_npmVersion": "1.4.9", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "finished@1.2.2", + "name": "finished", + "escapedName": "finished", + "rawSpec": "1.2.2", + "saveSpec": null, + "fetchSpec": "1.2.2" + }, + "_requiredBy": [ + "/send", + "/serve-static/send" + ], + "_resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", + "_shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", + "_spec": "finished@1.2.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\send", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/finished" + "bugs": { + "url": "https://github.com/expressjs/finished/issues" }, + "bundleDependencies": false, "dependencies": { "ee-first": "1.0.3" }, + "deprecated": false, + "description": "Execute a callback when a request closes, finishes, or errors", "devDependencies": { "istanbul": "0.2.10", "mocha": "~1.20.1", "should": "~4.0.1" }, + "directories": {}, + "dist": { + "shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", + "tarball": "http://registry.npmjs.org/finished/-/finished-1.2.2.tgz" + }, "engine": { "node": ">= 0.8.0" }, - "scripts": { - "test": "mocha --reporter spec test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/finished/issues" - }, "homepage": "https://github.com/expressjs/finished", - "_id": "finished@1.2.2", - "_shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", - "_from": "finished@1.2.2", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, + "license": "MIT", "maintainers": [ { "name": "jongleberry", @@ -66,11 +83,15 @@ "email": "fishrock123@rocketmail.com" } ], - "dist": { - "shasum": "41608eafadfd65683b46a1220bc4b1ec3daedcd8", - "tarball": "http://registry.npmjs.org/finished/-/finished-1.2.2.tgz" + "name": "finished", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/finished.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", - "readme": "ERROR: No README data found!" + "scripts": { + "test": "mocha --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "version": "1.2.2" } diff --git a/node_modules/express/node_modules/fresh/.npmignore b/node_modules/fresh/.npmignore similarity index 100% rename from node_modules/express/node_modules/fresh/.npmignore rename to node_modules/fresh/.npmignore diff --git a/node_modules/express/node_modules/fresh/History.md b/node_modules/fresh/History.md similarity index 100% rename from node_modules/express/node_modules/fresh/History.md rename to node_modules/fresh/History.md diff --git a/node_modules/express/node_modules/fresh/Makefile b/node_modules/fresh/Makefile similarity index 100% rename from node_modules/express/node_modules/fresh/Makefile rename to node_modules/fresh/Makefile diff --git a/node_modules/express/node_modules/fresh/Readme.md b/node_modules/fresh/Readme.md similarity index 100% rename from node_modules/express/node_modules/fresh/Readme.md rename to node_modules/fresh/Readme.md diff --git a/node_modules/express/node_modules/fresh/index.js b/node_modules/fresh/index.js similarity index 100% rename from node_modules/express/node_modules/fresh/index.js rename to node_modules/fresh/index.js diff --git a/node_modules/express/node_modules/fresh/package.json b/node_modules/fresh/package.json similarity index 64% rename from node_modules/express/node_modules/fresh/package.json rename to node_modules/fresh/package.json index c7214e3..bff0db1 100644 --- a/node_modules/express/node_modules/fresh/package.json +++ b/node_modules/fresh/package.json @@ -1,50 +1,73 @@ { - "name": "fresh", + "_from": "fresh@0.2.2", + "_id": "fresh@0.2.2", + "_inBundle": false, + "_integrity": "sha1-lzHc9WeMf660T7kDxPct9VGH+nc=", + "_location": "/fresh", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "_npmVersion": "1.3.15", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "fresh@0.2.2", + "name": "fresh", + "escapedName": "fresh", + "rawSpec": "0.2.2", + "saveSpec": null, + "fetchSpec": "0.2.2" + }, + "_requiredBy": [ + "/express", + "/send", + "/serve-static/send" + ], + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz", + "_shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", + "_spec": "fresh@0.2.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca", "url": "http://tjholowaychuk.com" }, - "description": "HTTP response freshness testing", - "version": "0.2.2", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/node-fresh.git" + "bugs": { + "url": "https://github.com/visionmedia/node-fresh/issues" }, + "bundleDependencies": false, "dependencies": {}, + "deprecated": false, + "description": "HTTP response freshness testing", "devDependencies": { "mocha": "*", "should": "*" }, + "directories": {}, + "dist": { + "shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", + "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz" + }, + "homepage": "https://github.com/visionmedia/node-fresh", "licenses": [ { "type": "MIT", "url": "https://github.com/visionmedia/node-fresh/blob/master/Readme.md#license" } ], - "bugs": { - "url": "https://github.com/visionmedia/node-fresh/issues" - }, - "homepage": "https://github.com/visionmedia/node-fresh", - "_id": "fresh@0.2.2", - "dist": { - "shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", - "tarball": "http://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz" - }, - "_from": "fresh@0.2.2", - "_npmVersion": "1.3.15", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, + "main": "index.js", "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "9731dcf5678c7faeb44fb903c4f72df55187fa77", - "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz" + "name": "fresh", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-fresh.git" + }, + "version": "0.2.2" } diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore b/node_modules/ipaddr.js/.npmignore similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/.npmignore rename to node_modules/ipaddr.js/.npmignore diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile b/node_modules/ipaddr.js/Cakefile similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/Cakefile rename to node_modules/ipaddr.js/Cakefile diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/LICENSE rename to node_modules/ipaddr.js/LICENSE diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/README.md rename to node_modules/ipaddr.js/README.md diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/ipaddr.min.js rename to node_modules/ipaddr.js/ipaddr.min.js diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/lib/ipaddr.js rename to node_modules/ipaddr.js/lib/ipaddr.js diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json similarity index 63% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json rename to node_modules/ipaddr.js/package.json index 609354d..e610357 100644 --- a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/package.json +++ b/node_modules/ipaddr.js/package.json @@ -1,56 +1,78 @@ { - "name": "ipaddr.js", - "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", - "version": "0.1.2", + "_from": "ipaddr.js@0.1.2", + "_id": "ipaddr.js@0.1.2", + "_inBundle": false, + "_integrity": "sha1-ah/T2FT1ACllw017vNm0qNSwRn4=", + "_location": "/ipaddr.js", + "_npmUser": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "_npmVersion": "1.3.10", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ipaddr.js@0.1.2", + "name": "ipaddr.js", + "escapedName": "ipaddr.js", + "rawSpec": "0.1.2", + "saveSpec": null, + "fetchSpec": "0.1.2" + }, + "_requiredBy": [ + "/proxy-addr" + ], + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz", + "_shasum": "6a1fd3d854f5002965c34d7bbcd9b4a8d4b0467e", + "_spec": "ipaddr.js@0.1.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\proxy-addr", "author": { "name": "Peter Zotov", "email": "whitequark@whitequark.org" }, - "directories": { - "lib": "./lib" + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" }, + "bundleDependencies": false, "dependencies": {}, + "deprecated": false, + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", "devDependencies": { "coffee-script": "~1.6", "nodeunit": "~0.5.3", "uglify-js": "latest" }, - "scripts": { - "test": "cake build test" + "directories": { + "lib": "./lib" + }, + "dist": { + "shasum": "6a1fd3d854f5002965c34d7bbcd9b4a8d4b0467e", + "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz" + }, + "engines": { + "node": ">= 0.2.5" }, + "homepage": "https://github.com/whitequark/ipaddr.js#readme", "keywords": [ "ip", "ipv4", "ipv6" ], - "repository": { - "type": "git", - "url": "git://github.com/whitequark/ipaddr.js" - }, "main": "./lib/ipaddr", - "engines": { - "node": ">= 0.2.5" - }, - "bugs": { - "url": "https://github.com/whitequark/ipaddr.js/issues" - }, - "_id": "ipaddr.js@0.1.2", - "dist": { - "shasum": "6a1fd3d854f5002965c34d7bbcd9b4a8d4b0467e", - "tarball": "http://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz" - }, - "_from": "ipaddr.js@0.1.2", - "_npmVersion": "1.3.10", - "_npmUser": { - "name": "whitequark", - "email": "whitequark@whitequark.org" - }, "maintainers": [ { "name": "whitequark", "email": "whitequark@whitequark.org" } ], - "_shasum": "6a1fd3d854f5002965c34d7bbcd9b4a8d4b0467e", - "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz" + "name": "ipaddr.js", + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "scripts": { + "test": "cake build test" + }, + "version": "0.1.2" } diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee b/node_modules/ipaddr.js/src/ipaddr.coffee similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/src/ipaddr.coffee rename to node_modules/ipaddr.js/src/ipaddr.coffee diff --git a/node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee b/node_modules/ipaddr.js/test/ipaddr.test.coffee similarity index 100% rename from node_modules/express/node_modules/proxy-addr/node_modules/ipaddr.js/test/ipaddr.test.coffee rename to node_modules/ipaddr.js/test/ipaddr.test.coffee diff --git a/node_modules/express/node_modules/send/node_modules/finished/.npmignore b/node_modules/media-typer/.npmignore similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/.npmignore rename to node_modules/media-typer/.npmignore diff --git a/node_modules/express/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md similarity index 100% rename from node_modules/express/node_modules/media-typer/HISTORY.md rename to node_modules/media-typer/HISTORY.md diff --git a/node_modules/express/node_modules/media-typer/README.md b/node_modules/media-typer/README.md similarity index 100% rename from node_modules/express/node_modules/media-typer/README.md rename to node_modules/media-typer/README.md diff --git a/node_modules/express/node_modules/media-typer/index.js b/node_modules/media-typer/index.js similarity index 100% rename from node_modules/express/node_modules/media-typer/index.js rename to node_modules/media-typer/index.js diff --git a/node_modules/express/node_modules/media-typer/package.json b/node_modules/media-typer/package.json similarity index 64% rename from node_modules/express/node_modules/media-typer/package.json rename to node_modules/media-typer/package.json index 7070f28..59d7eac 100644 --- a/node_modules/express/node_modules/media-typer/package.json +++ b/node_modules/media-typer/package.json @@ -1,51 +1,73 @@ { - "name": "media-typer", - "description": "Simple RFC 6838 media type parser and formatter", - "version": "0.2.0", + "_from": "media-typer@0.2.0", + "_id": "media-typer@0.2.0", + "_inBundle": false, + "_integrity": "sha1-2KBlITrf6qLnYyGitt2jb/YzWYQ=", + "_location": "/media-typer", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "media-typer@0.2.0", + "name": "media-typer", + "escapedName": "media-typer", + "rawSpec": "0.2.0", + "saveSpec": null, + "fetchSpec": "0.2.0" + }, + "_requiredBy": [ + "/express", + "/type-is" + ], + "_resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", + "_shasum": "d8a065213adfeaa2e76321a2b6dda36ff6335984", + "_spec": "media-typer@0.2.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/media-typer" + "bugs": { + "url": "https://github.com/expressjs/media-typer/issues" }, + "bundleDependencies": false, + "deprecated": false, + "description": "Simple RFC 6838 media type parser and formatter", "devDependencies": { "istanbul": "0.2.10", "mocha": "~1.20.1", "should": "~4.0.4" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/media-typer/issues" - }, - "homepage": "https://github.com/expressjs/media-typer", - "_id": "media-typer@0.2.0", + "directories": {}, "dist": { "shasum": "d8a065213adfeaa2e76321a2b6dda36ff6335984", "tarball": "http://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz" }, - "_from": "media-typer@0.2.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/media-typer", + "license": "MIT", "maintainers": [ { "name": "dougwilson", "email": "doug@somethingdoug.com" } ], - "directories": {}, - "_shasum": "d8a065213adfeaa2e76321a2b6dda36ff6335984", - "_resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz" + "name": "media-typer", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/media-typer.git" + }, + "scripts": { + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "version": "0.2.0" } diff --git a/node_modules/memory-pager/.travis.yml b/node_modules/memory-pager/.travis.yml new file mode 100644 index 0000000..1c4ab31 --- /dev/null +++ b/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/LICENSE b/node_modules/memory-pager/LICENSE similarity index 95% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/LICENSE rename to node_modules/memory-pager/LICENSE index a7ae8ee..56fce08 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/LICENSE +++ b/node_modules/memory-pager/LICENSE @@ -1,7 +1,6 @@ - The MIT License (MIT) -Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2017 Mathias Buus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/node_modules/memory-pager/README.md b/node_modules/memory-pager/README.md new file mode 100644 index 0000000..a4a9e86 --- /dev/null +++ b/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implmenting sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/node_modules/memory-pager/index.js b/node_modules/memory-pager/index.js new file mode 100644 index 0000000..fc633fc --- /dev/null +++ b/node_modules/memory-pager/index.js @@ -0,0 +1,96 @@ +module.exports = Pager + +function Pager (pageSize) { + if (!(this instanceof Pager)) return new Pager(pageSize) + + this.length = 0 + this.updates = [] + this.pages = new Array(16) + this.pageSize = pageSize || 1024 +} + +Pager.prototype.updated = function (page) { + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype.get = function (i, noAllocate) { + if (i >= this.pages.length) { + if (noAllocate) return + this.pages = grow(this.pages, i, this.length) + } + + var page = this.pages[i] + + if (!page && !noAllocate) { + page = this.pages[i] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + if (i >= this.pages.length) this.pages = grow(this.pages, i, this.length) + if (i >= this.length) this.length = i + 1 + + if (!buf) { + this.pages[i] = undefined + return + } + + var page = this.pages[i] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else this.pages[i] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + + for (var i = 0; i < list.length; i++) { + list[i] = this.pages[i] ? this.pages[i].buffer : empty + } + + return Buffer.concat(list) +} + +function grow (list, index, len) { + var nlen = list.length * 2 + while (nlen <= index) nlen *= 2 + + var twice = new Array(nlen) + for (var i = 0; i < len; i++) twice[i] = list[i] + return twice +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false +} diff --git a/node_modules/memory-pager/package.json b/node_modules/memory-pager/package.json new file mode 100644 index 0000000..ff2a2c3 --- /dev/null +++ b/node_modules/memory-pager/package.json @@ -0,0 +1,52 @@ +{ + "_from": "memory-pager@^1.0.2", + "_id": "memory-pager@1.1.0", + "_inBundle": false, + "_integrity": "sha512-Mf9OHV/Y7h6YWDxTzX/b4ZZ4oh9NSXblQL8dtPCOomOtZciEHxePR78+uHFLLlsk01A6jVHhHsQZZ/WcIPpnzg==", + "_location": "/memory-pager", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "memory-pager@^1.0.2", + "name": "memory-pager", + "escapedName": "memory-pager", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/sparse-bitfield" + ], + "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.1.0.tgz", + "_shasum": "9308915e0e972849fefbae6f8bc95d6b350e7344", + "_spec": "memory-pager@^1.0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\sparse-bitfield", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Access memory using small fixed sized buffers", + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/memory-pager", + "license": "MIT", + "main": "index.js", + "name": "memory-pager", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/memory-pager.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "1.1.0" +} diff --git a/node_modules/memory-pager/test.js b/node_modules/memory-pager/test.js new file mode 100644 index 0000000..1638210 --- /dev/null +++ b/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/node_modules/express/node_modules/merge-descriptors/.npmignore b/node_modules/merge-descriptors/.npmignore similarity index 100% rename from node_modules/express/node_modules/merge-descriptors/.npmignore rename to node_modules/merge-descriptors/.npmignore diff --git a/node_modules/express/node_modules/merge-descriptors/README.md b/node_modules/merge-descriptors/README.md similarity index 100% rename from node_modules/express/node_modules/merge-descriptors/README.md rename to node_modules/merge-descriptors/README.md diff --git a/node_modules/express/node_modules/merge-descriptors/component.json b/node_modules/merge-descriptors/component.json similarity index 100% rename from node_modules/express/node_modules/merge-descriptors/component.json rename to node_modules/merge-descriptors/component.json diff --git a/node_modules/express/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js similarity index 100% rename from node_modules/express/node_modules/merge-descriptors/index.js rename to node_modules/merge-descriptors/index.js diff --git a/node_modules/express/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json similarity index 60% rename from node_modules/express/node_modules/merge-descriptors/package.json rename to node_modules/merge-descriptors/package.json index 76673a2..ac61669 100644 --- a/node_modules/express/node_modules/merge-descriptors/package.json +++ b/node_modules/merge-descriptors/package.json @@ -1,42 +1,63 @@ { - "name": "merge-descriptors", - "description": "Merge objects using descriptors", - "version": "0.0.2", + "_from": "merge-descriptors@0.0.2", + "_id": "merge-descriptors@0.0.2", + "_inBundle": false, + "_integrity": "sha1-w2pSp4FDdRPFcnXzndnTF1FKyMc=", + "_location": "/merge-descriptors", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "_npmVersion": "1.3.17", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "merge-descriptors@0.0.2", + "name": "merge-descriptors", + "escapedName": "merge-descriptors", + "rawSpec": "0.0.2", + "saveSpec": null, + "fetchSpec": "0.0.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", + "_shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", + "_spec": "merge-descriptors@0.0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/component/merge-descriptors.git" - }, "bugs": { "url": "https://github.com/component/merge-descriptors/issues" }, - "scripts": { - "test": "make test;" - }, - "homepage": "https://github.com/component/merge-descriptors", - "_id": "merge-descriptors@0.0.2", + "bundleDependencies": false, + "deprecated": false, + "description": "Merge objects using descriptors", + "directories": {}, "dist": { "shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", "tarball": "http://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz" }, - "_from": "merge-descriptors@0.0.2", - "_npmVersion": "1.3.17", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, + "homepage": "https://github.com/component/merge-descriptors", + "license": "MIT", "maintainers": [ { "name": "jongleberry", "email": "jonathanrichardong@gmail.com" } ], - "directories": {}, - "_shasum": "c36a52a781437513c57275f39dd9d317514ac8c7", - "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz" + "name": "merge-descriptors", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "scripts": { + "test": "make test;" + }, + "version": "0.0.2" } diff --git a/node_modules/express/node_modules/methods/.npmignore b/node_modules/methods/.npmignore similarity index 100% rename from node_modules/express/node_modules/methods/.npmignore rename to node_modules/methods/.npmignore diff --git a/node_modules/express/node_modules/methods/History.md b/node_modules/methods/History.md similarity index 100% rename from node_modules/express/node_modules/methods/History.md rename to node_modules/methods/History.md diff --git a/node_modules/express/node_modules/methods/LICENSE b/node_modules/methods/LICENSE similarity index 100% rename from node_modules/express/node_modules/methods/LICENSE rename to node_modules/methods/LICENSE diff --git a/node_modules/express/node_modules/methods/Readme.md b/node_modules/methods/Readme.md similarity index 100% rename from node_modules/express/node_modules/methods/Readme.md rename to node_modules/methods/Readme.md diff --git a/node_modules/express/node_modules/methods/index.js b/node_modules/methods/index.js similarity index 100% rename from node_modules/express/node_modules/methods/index.js rename to node_modules/methods/index.js diff --git a/node_modules/express/node_modules/methods/package.json b/node_modules/methods/package.json similarity index 66% rename from node_modules/express/node_modules/methods/package.json rename to node_modules/methods/package.json index 692fd0b..e3a24ac 100644 --- a/node_modules/express/node_modules/methods/package.json +++ b/node_modules/methods/package.json @@ -1,48 +1,69 @@ { - "name": "methods", - "version": "1.0.1", - "description": "HTTP methods that node supports", - "main": "index.js", - "scripts": { - "test": "./node_modules/mocha/bin/mocha" + "_from": "methods@1.0.1", + "_id": "methods@1.0.1", + "_inBundle": false, + "_integrity": "sha1-dbyRlD3/19oDfPPusO1zoAN80Us=", + "_location": "/methods", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" }, - "keywords": [ - "http", - "methods" + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "methods@1.0.1", + "name": "methods", + "escapedName": "methods", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express" ], + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz", + "_shasum": "75bc91943dffd7da037cf3eeb0ed73a0037cd14b", + "_spec": "methods@1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "TJ Holowaychuk" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-methods.git" + "bugs": { + "url": "https://github.com/visionmedia/node-methods/issues" }, + "bundleDependencies": false, + "deprecated": false, + "description": "HTTP methods that node supports", "devDependencies": { "mocha": "1.17.x" }, - "bugs": { - "url": "https://github.com/visionmedia/node-methods/issues" - }, - "homepage": "https://github.com/visionmedia/node-methods", - "_id": "methods@1.0.1", + "directories": {}, "dist": { "shasum": "75bc91943dffd7da037cf3eeb0ed73a0037cd14b", "tarball": "http://registry.npmjs.org/methods/-/methods-1.0.1.tgz" }, - "_from": "methods@1.0.1", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, + "homepage": "https://github.com/visionmedia/node-methods", + "keywords": [ + "http", + "methods" + ], + "license": "MIT", + "main": "index.js", "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "75bc91943dffd7da037cf3eeb0ed73a0037cd14b", - "_resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz" + "name": "methods", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-methods.git" + }, + "scripts": { + "test": "./node_modules/mocha/bin/mocha" + }, + "version": "1.0.1" } diff --git a/node_modules/express/node_modules/methods/test/methods.js b/node_modules/methods/test/methods.js similarity index 100% rename from node_modules/express/node_modules/methods/test/methods.js rename to node_modules/methods/test/methods.js diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/.npmignore b/node_modules/mime-types/.npmignore similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/.npmignore rename to node_modules/mime-types/.npmignore diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/.travis.yml b/node_modules/mime-types/.travis.yml similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/.travis.yml rename to node_modules/mime-types/.travis.yml diff --git a/node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/LICENSE b/node_modules/mime-types/LICENSE similarity index 100% rename from node_modules/express/node_modules/send/node_modules/finished/node_modules/ee-first/LICENSE rename to node_modules/mime-types/LICENSE diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/Makefile b/node_modules/mime-types/Makefile similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/Makefile rename to node_modules/mime-types/Makefile diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/README.md b/node_modules/mime-types/README.md similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/README.md rename to node_modules/mime-types/README.md diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/SOURCES.md b/node_modules/mime-types/SOURCES.md similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/SOURCES.md rename to node_modules/mime-types/SOURCES.md diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/component.json b/node_modules/mime-types/component.json similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/component.json rename to node_modules/mime-types/component.json diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/lib/custom.json b/node_modules/mime-types/lib/custom.json similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/lib/custom.json rename to node_modules/mime-types/lib/custom.json diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/lib/index.js b/node_modules/mime-types/lib/index.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/lib/index.js rename to node_modules/mime-types/lib/index.js diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/lib/mime.json b/node_modules/mime-types/lib/mime.json similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/lib/mime.json rename to node_modules/mime-types/lib/mime.json diff --git a/node_modules/express/node_modules/accepts/node_modules/mime-types/lib/node.json b/node_modules/mime-types/lib/node.json similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/mime-types/lib/node.json rename to node_modules/mime-types/lib/node.json diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json b/node_modules/mime-types/package.json similarity index 66% rename from node_modules/express/node_modules/type-is/node_modules/mime-types/package.json rename to node_modules/mime-types/package.json index 10a028c..d223e8a 100644 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/package.json +++ b/node_modules/mime-types/package.json @@ -1,12 +1,42 @@ { - "name": "mime-types", - "description": "The ultimate javascript content-type utility.", - "version": "1.0.2", + "_from": "mime-types@~1.0.0", + "_id": "mime-types@1.0.2", + "_inBundle": false, + "_integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=", + "_location": "/mime-types", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.21", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "mime-types@~1.0.0", + "name": "mime-types", + "escapedName": "mime-types", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/accepts", + "/type-is" + ], + "_resolved": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", + "_shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", + "_spec": "mime-types@~1.0.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\accepts", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, + "bugs": { + "url": "https://github.com/expressjs/mime-types/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Jeremiah Senkpiel", @@ -14,37 +44,26 @@ "url": "https://searchbeam.jit.su" } ], - "repository": { - "type": "git", - "url": "https://github.com/expressjs/mime-types" - }, - "license": "MIT", - "main": "lib", + "deprecated": false, + "description": "The ultimate javascript content-type utility.", "devDependencies": { "co": "3", "cogent": "0", "mocha": "1", "should": "3" }, + "directories": {}, + "dist": { + "shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", + "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" + }, "engines": { "node": ">= 0.8.0" }, - "scripts": { - "test": "make test" - }, "gitHead": "e82b23836eb42003b8346fb31769da2fb7eb54e8", - "bugs": { - "url": "https://github.com/expressjs/mime-types/issues" - }, "homepage": "https://github.com/expressjs/mime-types", - "_id": "mime-types@1.0.2", - "_shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", - "_from": "mime-types@>=1.0.1 <1.1.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, + "license": "MIT", + "main": "lib", "maintainers": [ { "name": "jongleberry", @@ -59,10 +78,13 @@ "email": "doug@somethingdoug.com" } ], - "dist": { - "shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce", - "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" + "name": "mime-types", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/mime-types.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz" + "scripts": { + "test": "make test" + }, + "version": "1.0.2" } diff --git a/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/node_modules/mime/LICENSE similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/LICENSE rename to node_modules/mime/LICENSE diff --git a/node_modules/express/node_modules/send/node_modules/mime/README.md b/node_modules/mime/README.md similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/README.md rename to node_modules/mime/README.md diff --git a/node_modules/express/node_modules/send/node_modules/mime/mime.js b/node_modules/mime/mime.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/mime.js rename to node_modules/mime/mime.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/package.json b/node_modules/mime/package.json similarity index 63% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/package.json rename to node_modules/mime/package.json index 3ab7acc..41c5721 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/mime/package.json +++ b/node_modules/mime/package.json @@ -1,9 +1,42 @@ { + "_from": "mime@1.2.11", + "_id": "mime@1.2.11", + "_inBundle": false, + "_integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=", + "_location": "/mime", + "_npmUser": { + "name": "broofa", + "email": "robert@broofa.com" + }, + "_npmVersion": "1.3.6", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mime@1.2.11", + "name": "mime", + "escapedName": "mime", + "rawSpec": "1.2.11", + "saveSpec": null, + "fetchSpec": "1.2.11" + }, + "_requiredBy": [ + "/send", + "/serve-static/send" + ], + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "_spec": "mime@1.2.11", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\send", "author": { "name": "Robert Kieffer", "email": "robert@broofa.com", "url": "http://github.com/broofa" }, + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Benjamin Thomas", @@ -12,33 +45,20 @@ } ], "dependencies": {}, + "deprecated": false, "description": "A comprehensive library for mime-type mapping", "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", + "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + }, + "homepage": "https://github.com/broofa/node-mime#readme", "keywords": [ "util", "mime" ], "main": "mime.js", - "name": "mime", - "repository": { - "url": "https://github.com/broofa/node-mime", - "type": "git" - }, - "version": "1.2.11", - "bugs": { - "url": "https://github.com/broofa/node-mime/issues" - }, - "_id": "mime@1.2.11", - "dist": { - "shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "tarball": "http://registry.npmjs.org/mime/-/mime-1.2.11.tgz" - }, - "_from": "mime@1.2.11", - "_npmVersion": "1.3.6", - "_npmUser": { - "name": "broofa", - "email": "robert@broofa.com" - }, "maintainers": [ { "name": "broofa", @@ -49,7 +69,10 @@ "email": "benjamin@benjaminthomas.org" } ], - "directories": {}, - "_shasum": "58203eed86e3a5ef17aed2b7d9ebd47f0a60dd10", - "_resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz" + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "version": "1.2.11" } diff --git a/node_modules/express/node_modules/send/node_modules/mime/test.js b/node_modules/mime/test.js similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/test.js rename to node_modules/mime/test.js diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/mime.types b/node_modules/mime/types/mime.types similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/types/mime.types rename to node_modules/mime/types/mime.types diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/node.types b/node_modules/mime/types/node.types similarity index 100% rename from node_modules/express/node_modules/send/node_modules/mime/types/node.types rename to node_modules/mime/types/node.types diff --git a/node_modules/mongodb-core/HISTORY.md b/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..d4cd9cc --- /dev/null +++ b/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,1052 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.1.8](https://github.com/mongodb-js/mongodb-core/compare/v3.1.7...v3.1.8) (2018-11-05) + + +### Bug Fixes + +* **sspi:** correct auth process for SSPI ([808ab21](https://github.com/mongodb-js/mongodb-core/commit/808ab21)) +* **uri_parser:** add `replSet` to exemption list for number coercion ([d00b1ab](https://github.com/mongodb-js/mongodb-core/commit/d00b1ab)) + + + + +## [3.1.7](https://github.com/mongodb-js/mongodb-core/compare/v3.1.6...v3.1.7) (2018-10-10) + + +### Bug Fixes + +* **uri-parser:** persist default database when authSource present ([aa601d3](https://github.com/mongodb-js/mongodb-core/commit/aa601d3)) + + + + +## [3.1.6](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.6) (2018-10-09) + + +### Bug Fixes + +* **srv-parsing:** ensure parse options are propogated to txt lookup ([923ceb0](https://github.com/mongodb-js/mongodb-core/commit/923ceb0)) +* **uri-parser:** add exemption list for number coercion in options ([82896ea](https://github.com/mongodb-js/mongodb-core/commit/82896ea)) + + + + +## [3.1.5](https://github.com/mongodb-js/mongodb-core/compare/v3.1.4...v3.1.5) (2018-09-15) + +### Bug Fixes + +* **connection:** Revert fast fallback due to Atlas connect issues ([3133fc3](https://github.com/mongodb-js/mongodb-core/commit/3133fc3)) + + + +## [3.1.4](https://github.com/mongodb-js/mongodb-core/compare/v3.1.3...v3.1.4) (2018-09-14) + + +### Bug Fixes + +* **apm:** fix upconversion for OP_QUERY in apm ([f969bee](https://github.com/mongodb-js/mongodb-core/commit/f969bee)) +* **gssapi:** check lowercase and camelCase gssapiServiceName option ([bf0315d](https://github.com/mongodb-js/mongodb-core/commit/bf0315d)) +* **test:** do not check deep equality when test.auth.db is null ([7d3c057](https://github.com/mongodb-js/mongodb-core/commit/7d3c057)) +* **uri_parser:** use admin as default auth.db ([345e6af](https://github.com/mongodb-js/mongodb-core/commit/345e6af)) + + +### Features + +* **connection:** Implement fast fallback ([622394a](https://github.com/mongodb-js/mongodb-core/commit/622394a)) + + + + +## [3.1.3](https://github.com/mongodb-js/mongodb-core/compare/v3.1.2...v3.1.3) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([728d897](https://github.com/mongodb-js/mongodb-core/commit/728d897)) +* **EJSON:** export the result of optionally requiring EJSON ([645d73d](https://github.com/mongodb-js/mongodb-core/commit/645d73d)) + + +### Features + +* **kerberos:** bump kerberos dependency to `^1.0.0` ([1155ebe](https://github.com/mongodb-js/mongodb-core/commit/1155ebe)) +* **standard-version:** automate part of the release process ([4c768c4](https://github.com/mongodb-js/mongodb-core/commit/4c768c4)) + + + + +## [3.1.2](https://github.com/mongodb-js/mongodb-core/compare/v3.1.1...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **mongos:** fix connection leak when mongos reconnects ([2453746](https://github.com/mongodb-js/mongodb-core/commit/2453746)) + + +### Features + +* **bson:** update to bson ^1.1.x ([952a2f0](https://github.com/mongodb-js/mongodb-core/commit/952a2f0)) + + + + +## [3.1.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.1) (2018-08-13) + + +### Bug Fixes + +* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) +* **buffer:** replace deprecated Buffer constructor ([7c71e19](https://github.com/mongodb-js/mongodb-core/commit/7c71e19)) +* **commands:** check doc.cursor errors ([4f2b263](https://github.com/mongodb-js/mongodb-core/commit/4f2b263)) +* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) +* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) +* **cursor:** typo in _find() ([95f7fd2](https://github.com/mongodb-js/mongodb-core/commit/95f7fd2)) +* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) +* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) +* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) +* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) +* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) +* **read-preference:** correct server sort for `nearest` selection ([dd4eb9a](https://github.com/mongodb-js/mongodb-core/commit/dd4eb9a)) +* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) +* **server:** correct typo using `this` instead of `server` ([c54f040](https://github.com/mongodb-js/mongodb-core/commit/c54f040)) +* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) +* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) +* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) +* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) +* **uri_parser:** ensure default port is 27017 ([426a95e](https://github.com/mongodb-js/mongodb-core/commit/426a95e)) +* **uri-parser:** Incorrect parsing of arrays ([fcff104](https://github.com/mongodb-js/mongodb-core/commit/fcff104)) +* **uri-parser:** Parse comma separated option values ([2dd1de0](https://github.com/mongodb-js/mongodb-core/commit/2dd1de0)) +* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) + + +### Features + +* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) +* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) +* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) +* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) +* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) +* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) +* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) +* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) +* **monitoring:** add support for server monitoring to `Server` ([30a394d](https://github.com/mongodb-js/mongodb-core/commit/30a394d)) +* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) +* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) +* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) +* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) +* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) +* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) +* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) +* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) + + + + +# [3.1.0](https://github.com/mongodb-js/mongodb-core/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **auth:** prevent stalling on authentication when connected ([6b4ac89](https://github.com/mongodb-js/mongodb-core/commit/6b4ac89)) +* **cursor:** check for session presence independently ([7c76c62](https://github.com/mongodb-js/mongodb-core/commit/7c76c62)) +* **cursor:** check for sessions independently in core cursor ([cb5df28](https://github.com/mongodb-js/mongodb-core/commit/cb5df28)) +* **error:** attach command response to MongoWriteConcernError ([#322](https://github.com/mongodb-js/mongodb-core/issues/322)) ([24c5d06](https://github.com/mongodb-js/mongodb-core/commit/24c5d06)) +* **getmore-killcursor:** slaveOk shall not be included on these ([40fb2f4](https://github.com/mongodb-js/mongodb-core/commit/40fb2f4)) +* **kerberos:** loosen restrictions on kerberos versions ([c4add26](https://github.com/mongodb-js/mongodb-core/commit/c4add26)) +* **mongos:** use `incrementTransactionNumber` directly on session ([e230d54](https://github.com/mongodb-js/mongodb-core/commit/e230d54)) +* **pool:** ensure that lsid is sent in get requests to mongos ([ae820f6](https://github.com/mongodb-js/mongodb-core/commit/ae820f6)) +* **sdam:** we can't use Array.includes yet ([9c3b5ab](https://github.com/mongodb-js/mongodb-core/commit/9c3b5ab)) +* **sessions:** add `toBSON` method to `ClientSession` ([d95a4d1](https://github.com/mongodb-js/mongodb-core/commit/d95a4d1)) +* **sessions:** never send `endSessions` from a `ClientSession` ([05ffe82](https://github.com/mongodb-js/mongodb-core/commit/05ffe82)) +* **topology-description:** we can't use Object.values yet ([91df350](https://github.com/mongodb-js/mongodb-core/commit/91df350)) +* **transactions:** do not send txnNumber for non-write commands ([#308](https://github.com/mongodb-js/mongodb-core/issues/308)) ([eb67b1a](https://github.com/mongodb-js/mongodb-core/commit/eb67b1a)) +* **wireprotocol:** only send bypassDocumentValidation if true ([a81678b](https://github.com/mongodb-js/mongodb-core/commit/a81678b)) + + +### Features + +* **auth:** adds saslprep and SCRAM-SHA-256 ([506c087](https://github.com/mongodb-js/mongodb-core/commit/506c087)) +* **cursor:** implement cursor for new sdam implementation ([f289226](https://github.com/mongodb-js/mongodb-core/commit/f289226)) +* **cursor:** store operation time from initial query ([55e761e](https://github.com/mongodb-js/mongodb-core/commit/55e761e)) +* **error:** add more specific error type for write concern errors ([347c5d7](https://github.com/mongodb-js/mongodb-core/commit/347c5d7)) +* **Error:** adding error metadata field ([33be560](https://github.com/mongodb-js/mongodb-core/commit/33be560)) +* **kerberos:** expose warning for kerberos mismatch versions ([efc0e43](https://github.com/mongodb-js/mongodb-core/commit/efc0e43)) +* **max-staleness:** properly support a max staleness reducer ([d9c5c16](https://github.com/mongodb-js/mongodb-core/commit/d9c5c16)) +* **MongoTimeoutError:** add common class for timeout events ([c5b4752](https://github.com/mongodb-js/mongodb-core/commit/c5b4752)) +* **op-compressed:** add support for OP_COMPRESSED to new sdam impl ([8deec9b](https://github.com/mongodb-js/mongodb-core/commit/8deec9b)) +* **retryableWrites:** adding more support for retries ([d4c1597](https://github.com/mongodb-js/mongodb-core/commit/d4c1597)) +* **sdam-monitoring:** add basic monitoring for new Topology type ([bb0c522](https://github.com/mongodb-js/mongodb-core/commit/bb0c522)) +* **server:** add `command` support to new server class ([d9a8c05](https://github.com/mongodb-js/mongodb-core/commit/d9a8c05)) +* **server-selection:** add basic support for server selection ([ccc5e1d](https://github.com/mongodb-js/mongodb-core/commit/ccc5e1d)) +* **topology:** introduce a single Topology type, and test runner ([f35d773](https://github.com/mongodb-js/mongodb-core/commit/f35d773)) +* **topology-description:** add helper method for server ownership ([2c64c75](https://github.com/mongodb-js/mongodb-core/commit/2c64c75)) +* **txns:** add initial transaction interface for sessions ([ed76be0](https://github.com/mongodb-js/mongodb-core/commit/ed76be0)) + + + + +## [3.0.6](https://github.com/mongodb-js/mongodb-core/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **2.6-protocol:** kill cursor callback is called by pool now ([65f2bf7](https://github.com/mongodb-js/mongodb-core/commit/65f2bf7)) +* **evergreen:** change name to id ([9303e12](https://github.com/mongodb-js/mongodb-core/commit/9303e12)) +* **evergreen:** change nvm path to local ([e42ea5b](https://github.com/mongodb-js/mongodb-core/commit/e42ea5b)) +* **evergreen:** pass in flag through npm scripts ([85708dd](https://github.com/mongodb-js/mongodb-core/commit/85708dd)) +* **pool:** ensure noResponse callback is only called if cb exists ([5281605](https://github.com/mongodb-js/mongodb-core/commit/5281605)) +* **replset:** only remove primary if primary is there ([1acd288](https://github.com/mongodb-js/mongodb-core/commit/1acd288)) +* **test-environments:** ensure all servers run on separate ports ([b63e5d8](https://github.com/mongodb-js/mongodb-core/commit/b63e5d8)) +* **uri_parser:** support a default database on mongodb+srv uris ([be01ffe](https://github.com/mongodb-js/mongodb-core/commit/be01ffe)) + + +### Features + +* **apm:** add events for command monitoring support in core ([37dce9c](https://github.com/mongodb-js/mongodb-core/commit/37dce9c)) +* **evergreen:** add evergreen config based on drivers skeleton ([b71da99](https://github.com/mongodb-js/mongodb-core/commit/b71da99)) +* **evergreen:** use evergreen flag when running tests ([55dff3b](https://github.com/mongodb-js/mongodb-core/commit/55dff3b)) + + + + +## [3.0.5](https://github.com/mongodb-js/mongodb-core/compare/v3.0.4...v3.0.5) (2018-03-14) + + +### Features + +* **sessions:** adding implicit cursor session support ([1607321](https://github.com/mongodb-js/mongodb-core/commit/1607321)) + + + + +## [3.0.4](https://github.com/mongodb-js/mongodb-core/compare/v3.0.3...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **connection:** ensure socket options are applied to ssl sockets ([e5ff927](https://github.com/mongodb-js/mongodb-core/commit/e5ff927)) + + + + +## [3.0.3](https://github.com/mongodb-js/mongodb-core/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **connection:** make pool not try to reconnect forever when reconnectTries = 0 ([#275](https://github.com/mongodb-js/mongodb-core/issues/275)) ([2d3fa98](https://github.com/mongodb-js/mongodb-core/commit/2d3fa98)), closes [Automattic/mongoose#6028](https://github.com/Automattic/mongoose/issues/6028) +* **retryableWrites:** only remove primary after retry ([#274](https://github.com/mongodb-js/mongodb-core/issues/274)) ([7ac171e](https://github.com/mongodb-js/mongodb-core/commit/7ac171e)) +* **sessions:** actually allow ending of sessions ([2b81bb6](https://github.com/mongodb-js/mongodb-core/commit/2b81bb6)) +* **uri-parser:** do not use `hasOwnProperty` to detect ssl ([69d16c7](https://github.com/mongodb-js/mongodb-core/commit/69d16c7)) + + +### Features + +* **sessions:** adding endAllPooledSessions helper method ([d7804ed](https://github.com/mongodb-js/mongodb-core/commit/d7804ed)) + + + + +## [3.0.2](https://github.com/mongodb-js/mongodb-core/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **cursor:** check for autoReconnect option only for single server ([645d6df](https://github.com/mongodb-js/mongodb-core/commit/645d6df)) + + +### Features + +* **mongodb+srv:** add support for mongodb+srv to the uri parser ([19b42ce](https://github.com/mongodb-js/mongodb-core/commit/19b42ce)) +* **uri-parser:** add initial implementation of uri parser for core ([8f797a7](https://github.com/mongodb-js/mongodb-core/commit/8f797a7)) +* **uri-parser:** expose the connection string parser as api ([fdeca2f](https://github.com/mongodb-js/mongodb-core/commit/fdeca2f)) + + + + +## [3.0.1](https://github.com/mongodb-js/mongodb-core/compare/v3.0.0...v3.0.1) (2017-12-24) + + +### Bug Fixes + +* **connection:** correct erroneous use of `this` in helper method ([06b9388](https://github.com/mongodb-js/mongodb-core/commit/06b9388)) + + + + +# [3.0.0](https://github.com/christkv/mongodb-core/compare/v3.0.0-rc0...v3.0.0) (2017-12-23) + + +### Bug Fixes + +* **connection:** ensure connection cleanup before fallback retry ([de62615](https://github.com/christkv/mongodb-core/commit/de62615)) +* **mock-server:** expose potential errors in message handlers ([65dcca4](https://github.com/christkv/mongodb-core/commit/65dcca4)) +* **mongos:** remove listener on destroy event ([243e942](https://github.com/christkv/mongodb-core/commit/243e942)), closes [#257](https://github.com/christkv/mongodb-core/issues/257) +* **sdam:** more explicit wire protocol error message ([6d6d19a](https://github.com/christkv/mongodb-core/commit/6d6d19a)) +* **secondaries:** fixes connection with secondary readPreference ([#258](https://github.com/christkv/mongodb-core/issues/258)) ([0060ad7](https://github.com/christkv/mongodb-core/commit/0060ad7)) +* **sessions:** ensure that we ignore session details from arbiters ([de0105c](https://github.com/christkv/mongodb-core/commit/de0105c)) +* **sharded-tests:** add `shardsvr` cmdline opt, wait for async fns ([867b080](https://github.com/christkv/mongodb-core/commit/867b080)) + + +### Features + +* **connection:** attempt both ipv6 and ipv4 when no family entered ([#260](https://github.com/christkv/mongodb-core/issues/260)) ([107bae5](https://github.com/christkv/mongodb-core/commit/107bae5)) + + + + +# 3.0.0-rc0 (2017-12-05) + + +### Bug Fixes + +* **auth-plain:** only use BSON -after- requiring it ([4934adf](https://github.com/christkv/mongodb-core/commit/4934adf)) +* **auth-scram:** cache the ScramSHA1 salted passwords up to 200 entries ([31ef03a](https://github.com/christkv/mongodb-core/commit/31ef03a)) +* **client-session:** don't report errors for endSessions commands ([c34eaf5](https://github.com/christkv/mongodb-core/commit/c34eaf5)) +* **connection:** default `family` to undefined rather than 4 ([c1b5e04](https://github.com/christkv/mongodb-core/commit/c1b5e04)) +* **connection:** fixing leak in 3.0.0 ([#235](https://github.com/christkv/mongodb-core/issues/235)) ([fc669c0](https://github.com/christkv/mongodb-core/commit/fc669c0)) +* **cursor:** avoid waiting for reconnect if reconnect disabled ([43e9b23](https://github.com/christkv/mongodb-core/commit/43e9b23)) +* **cursor:** callback with server response on `_find` ([6999459](https://github.com/christkv/mongodb-core/commit/6999459)) +* **errors:** export MongoError and MongoNetworkError at top-level ([972064a](https://github.com/christkv/mongodb-core/commit/972064a)) +* **errors:** throw MongoNetworkError from more places ([2cec239](https://github.com/christkv/mongodb-core/commit/2cec239)) +* **errors:** use subclassing for MongoNetworkError ([a132830](https://github.com/christkv/mongodb-core/commit/a132830)) +* **errors:** use util.inherits() and protect edge case ([c953246](https://github.com/christkv/mongodb-core/commit/c953246)) +* **mocha_server_tests:** rename confusing variable to fix tests ([a9fbae2](https://github.com/christkv/mongodb-core/commit/a9fbae2)) +* **mock-tests:** ensure all servers are properly cleaned up ([5dafc86](https://github.com/christkv/mongodb-core/commit/5dafc86)) +* **package:** upgrade mongodb-test-runner with bug fix ([5b2e99e](https://github.com/christkv/mongodb-core/commit/5b2e99e)) +* **pool:** check topology exists before verifying session support ([0aa146d](https://github.com/christkv/mongodb-core/commit/0aa146d)) +* **pool:** ensure inUse and connecting queues are cleared on reauth ([aa2840d](https://github.com/christkv/mongodb-core/commit/aa2840d)) +* **pool:** ensure that errors are propagated on force destroy ([8f8ad56](https://github.com/christkv/mongodb-core/commit/8f8ad56)) +* **pool:** ensure workItem is not null before accessing properties ([2143963](https://github.com/christkv/mongodb-core/commit/2143963)) +* **pool_tests:** remove .only ([8172137](https://github.com/christkv/mongodb-core/commit/8172137)) +* **retryable-writes:** don't increment `txnNumber` on retries ([e7c2242](https://github.com/christkv/mongodb-core/commit/e7c2242)) +* **retryable-writes:** network errors are retryable, inverted logic ([2727551](https://github.com/christkv/mongodb-core/commit/2727551)) +* **scram:** cache salted data, not the original data ([0cbe95f](https://github.com/christkv/mongodb-core/commit/0cbe95f)) +* **SDAM:** emit SDAM events on close and reconnect ([3451ff0](https://github.com/christkv/mongodb-core/commit/3451ff0)) +* **server:** avoid waiting for reconnect if reconnect disabled ([611a352](https://github.com/christkv/mongodb-core/commit/611a352)) +* **server:** correct minor typo in porting 2.x patch ([d92efec](https://github.com/christkv/mongodb-core/commit/d92efec)) +* **server_tests:** change 'this' to 'self' in some server tests ([992d9e9](https://github.com/christkv/mongodb-core/commit/992d9e9)) +* **server_tests:** fix errors in broken test ([1602e4d](https://github.com/christkv/mongodb-core/commit/1602e4d)) +* **server-session-pool:** don't add expired sessions to the pool ([8f48b89](https://github.com/christkv/mongodb-core/commit/8f48b89)) +* **server-session-pool:** ensure the queue is LIFO ([ac68e76](https://github.com/christkv/mongodb-core/commit/ac68e76)) +* **utils:** don't throw if no snappy ([55bf2ad](https://github.com/christkv/mongodb-core/commit/55bf2ad)) +* **wire-protocol:** 2.6 killCursor should not way for reply ([7337d91](https://github.com/christkv/mongodb-core/commit/7337d91)) + + +### Features + +* **cluster-time:** ensure clusterTime makes it to outgoing commands ([e700b79](https://github.com/christkv/mongodb-core/commit/e700b79)) +* **cluster-time:** track incoming cluster time gossiping ([c910706](https://github.com/christkv/mongodb-core/commit/c910706)) +* **compression:** implement wire protocol compression support ([2356ffb](https://github.com/christkv/mongodb-core/commit/2356ffb)) +* **connection-spy:** add class for monitoring active connections ([6dd6db3](https://github.com/christkv/mongodb-core/commit/6dd6db3)) +* **errors:** create MongoNetworkError ([df12740](https://github.com/christkv/mongodb-core/commit/df12740)) +* **inital-cluster-time:** allow session to define initia value ([e3a1c8b](https://github.com/christkv/mongodb-core/commit/e3a1c8b)) +* **mock:** support a means of consistently cleaning up mock servers ([ab3b70b](https://github.com/christkv/mongodb-core/commit/ab3b70b)) +* **mock-server:** add the ability to set a message handler ([9a8b815](https://github.com/christkv/mongodb-core/commit/9a8b815)) +* **operation-time:** track operationTime in relevant sessions ([8d512f1](https://github.com/christkv/mongodb-core/commit/8d512f1)) +* **pool:** introduce the concept of a minimum pool size ([b01b1f8](https://github.com/christkv/mongodb-core/commit/b01b1f8)) +* **replset:** more verbose replica set errors emission ([6d5eccd](https://github.com/christkv/mongodb-core/commit/6d5eccd)) +* **retryable-writes:** add mongos support for retryable writes ([7778067](https://github.com/christkv/mongodb-core/commit/7778067)) +* **retryable-writes:** initial support on replicasets ([73ac688](https://github.com/christkv/mongodb-core/commit/73ac688)) +* **retryable-writes:** retry on "not master" stepdown errors ([028aec7](https://github.com/christkv/mongodb-core/commit/028aec7)) +* **server-check:** reintroduce server version check ([486aace](https://github.com/christkv/mongodb-core/commit/486aace)) +* **server-session-pool:** implement session pool per spect ([a1d5b22](https://github.com/christkv/mongodb-core/commit/a1d5b22)) +* **session:** allow `session` options to be passed to write cmds ([5da75e4](https://github.com/christkv/mongodb-core/commit/5da75e4)) +* **sessions:** add equality operator to ease readability ([6510d7d](https://github.com/christkv/mongodb-core/commit/6510d7d)) +* **sessions:** export all sessions types on the top level ([35265b3](https://github.com/christkv/mongodb-core/commit/35265b3)) +* **sessions:** support sessions with cursors with find/getMore ([a016602](https://github.com/christkv/mongodb-core/commit/a016602)) +* **sessions:** track `logicalSessionTimeoutMinutes` for sessions ([11865bf](https://github.com/christkv/mongodb-core/commit/11865bf)) +* **ssl:** adding ssl options ciphers and ecdhCurve ([c839d5c](https://github.com/christkv/mongodb-core/commit/c839d5c)) +* **test/:** convert server_tests, undefined_tests, replset_tests, replset_state_tests, and repleset_server_selection_tests to run with mongodb-test-runner ([3a7c5fd](https://github.com/christkv/mongodb-core/commit/3a7c5fd)) + + +2.1.16 2017-10-11 +----------------- +* avoid waiting for reconnect if reconnect disabled in Server topology +* avoid waiting for reconnect if reconnect disabled in Cursor +* NODE-990 cache the ScramSHA1 salted passwords up to 200 entries +* NODE-1153 ensure that errors are propagated on force destroy +* NODE-1153 ensure inUse and connecting queues are cleared on reauth + +2.1.15 2017-08-08 +----------------- +* Emit SDAM events on close and reconnect + +2.1.14 2017-07-07 +----------------- +* NODE-1073 updates scram.js hi() algorithm to utilize crypto.pbkdf2Sync() +* NODE-1049 only include primary server if there are no secondary servers for + readPrefrence secondaryPreferred +* moved `assign` polyfill to shared utils, replace usage of `extend` in tests + +2.1.13 2017-06-19 +----------------- +* NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. +* Use actual server type in standalone SDAM events. + +2.1.12 2017-06-02 +----------------- +* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Minor fix to report the correct state on error. +* NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). +* Fix require_optional loading of bson-ext. +* Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1014 Set socketTimeout to default to 360 seconds. +* NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + +2.1.11 2017-05-22 +----------------- +* NODE-987 Clear out old intervalIds on when calling topologyMonitor. +* NODE-987 Moved filtering to pingServer method and added test case. +* Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). +* NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interva. + +2.1.10 2017-04-18 +----------------- +* NODE-981 delegate auth to replset/mongos if inTopology is set. +* NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. +* Remove dynamic require (Issue #175, https://github.com/tellnes). +* NODE-696 Handle interrupted error for createIndexes. +* Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. +* NODE-966 promoteValues not being promoted correctly to getMore. +* Merged in fix for flushing out monitoring operations. + +2.1.9 2017-03-17 +---------------- +* Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. +* Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. +* Ensure SSL error propegates better for Replset connections when there is a SSL validation error. +* NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. +* NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.1.8 2017-02-13 +---------------- +* NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. +* NODE-927 fixes issue where authentication was performed against arbiter instances. +* NODE-915 Normalize all host names to avoid comparison issues. +* Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. + +2.1.7 2017-01-24 +---------------- +* NODE-919 ReplicaSet connection does not close immediately (Issue #156). +* NODE-901 Fixed bug when normalizing host names. +* NODE-909 Fixed readPreference issue caused by direct connection to primary. +* NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. + +2.1.6 2017-01-13 +---------------- +* NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.1.5 2017-01-11 +---------------- +* updated bson and bson-ext dependencies to 1.0.4 to work past early node 4.x.x version having a broken Buffer.from implementation. + +2.1.4 2017-01-03 +---------------- +* updated bson and bson-ext dependencies to 1.0.3 due to util.inspect issue with ObjectId optimizations. + +2.1.3 2017-01-03 +---------------- +* Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining +* Moved replicaset monitoring away from serial mode and to parallel mode. +* updated bson and bson-ext dependencies to 1.0.2. + +2.1.2 2016-12-10 +---------------- +* Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. +* Emit reconnect event in primary joining when in connected status for a replicaset. + +2.1.1 2016-12-08 +---------------- +* Updated bson library to 1.0.1. +* Added optional support for bson-ext 1.0.1. + +2.1.0 2016-12-05 +---------------- +* Updated bson library to 1.0.0. +* Added optional support for bson-ext 1.0.0. +* Expose property parserType allowing for identification of currently configured parser. + +2.0.14 2016-11-29 +----------------- +* Updated bson library to 0.5.7. +* Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). +* Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). +* Only check isConnected against availableConnections (Issue #142). +* NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. +* Set default servername to host is not passed through for sni. +* Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). +* NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. +* NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. +* NODE-850 Update Max Staleness implementation. +* NODE-849 username no longer required for MONGODB-X509 auth. +* NODE-848 BSON Regex flags must be alphabetically ordered. +* NODE-846 Create notice for all third party libraries. +* NODE-843 Executing bulk operations overwrites write concern parameter. +* NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. +* NODE-840 Resync CRUD spec tests. +* Unescapable while(true) loop (Issue #152). + +2.0.13 2016-10-21 +----------------- +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). +* Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). +* Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). +* NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). + +2.0.12 2016-09-15 +----------------- +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. + +2.0.11 2016-08-29 +----------------- +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propagated in same fashion as promoteValues and promoteLongs + +2.0.10 2016-08-23 +----------------- +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.0.9 2016-08-19 +---------------- +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.0.8 2016-08-16 +---------------- +* Allow execution of store operations indepent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Wrap callback in nextTick to ensure exceptions are thrown correctly. + +2.0.7 2016-07-28 +---------------- +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. +* Initial max staleness implementation for ReplSet and Mongos for 3.4 support. +* Added handling of collation for 3.4 support. + +2.0.6 2016-07-19 +---------------- +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.0.5 2016-07-15 +---------------- +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.0.4 2016-07-11 +----------------- +* Updated bson to version 0.5.1. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.0.3 2016-07-08 +----------------- +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. + +2.0.2 2016-07-06 +----------------- +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.0.1 2016-07-05 +----------------- +* Added missing logout method on mongos proxy topology. +* Fixed logger error serialization issue. +* Documentation fixes. + +2.0.0 2016-07-05 +----------------- +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. + +1.3.21 2016-05-30 +----------------- +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +1.3.20 2016-05-25 +----------------- +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +1.3.19 2016-05-17 +----------------- +- Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +- Set keepAlive to false by default to work around bug in node.js for Windows XP and Windows 2003. +- Ensure replicaset topology destroy is never called by SDAM. +- Ensure all paths are correctly returned on inspectServer in replset. + +1.3.18 2016-04-27 +----------------- +- Hardened cursor connection handling for getMore and killCursor to ensure mid operation connection kill does not throw null exception. +- Fixes for Node 6.0 support. + +1.3.17 2016-04-26 +----------------- +- Added improved handling of reconnect when topology is a single server. +- Added better handling of $query queries passed down for 3.2 or higher. +- Introduced getServerFrom method to topologies to let cursor grab a new pool for getMore and killCursors commands and not use connection pipelining. +- NODE-693 Move authentication to be after ismaster call to avoid authenticating against arbiters. + +1.3.16 2016-04-07 +----------------- +- Only call unref on destroy if it exists to ensure proper working destroy method on early node v0.10.x versions. + +1.3.15 2016-04-06 +----------------- +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +1.3.14 2016-04-01 +----------------- +- Ensure server inquireServerState exits immediately on server.destroy call. +- Refactored readPreference handling in 2.4, 2.6 and 3.2 wire protocol handling. + +1.3.13 2016-03-30 +----------------- +- Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +1.3.12 2016-03-29 +----------------- +- Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. + +1.3.11 2016-03-29 +----------------- +- isConnected method for mongos uses same selection code as getServer. +- Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +1.3.10 2016-03-22 +----------------- +- SDAM Monitoring emits diff for Replicasets to simplify detecting the state changes. +- SDAM Monitoring correctly emits Mongos as serverDescriptionEvent. + +1.3.9 2016-03-20 +---------------- +- Removed monitoring exclusive connection, should resolve timeouts and reconnects on idle replicasets where haInteval > socketTimeout. + +1.3.8 2016-03-18 +---------------- +- Implements the SDAM monitoring specification. +- Fix issue where cursor would error out and not be buffered when primary is not connected. + +1.3.7 2016-03-16 +---------------- +- Fixed issue with replicasetInquirer where it could stop performing monitoring if there was no servers available. + +1.3.6 2016-03-15 +---------------- +- Fixed raise condition where multiple replicasetInquirer operations could be started in parallel creating redundant connections. + +1.3.5 2016-03-14 +---------------- +- Handle rogue SSL exceptions (Issue #85, https://github.com/durran). + +1.3.4 2016-03-14 +---------------- +- Added unref options on server, replicaset and mongos (Issue #81, https://github.com/allevo) +- cursorNotFound flag always false (Issue #83, https://github.com/xgfd) +- refactor of events emission of fullsetup and all events (Issue #84, https://github.com/xizhibei) + +1.3.3 2016-03-08 +---------------- +- Added support for promoteLongs option for command function. +- Return connection if no callback available +- Emit connect event when server reconnects after initial connection failed (Issue #76, https://github.com/vkarpov15) +- Introduced optional monitoringSocketTimeout option to allow better control of SDAM monitoring timeouts. +- Made monitoringSocketTimeout default to 30000 if no connectionTimeout value specified or if set to 0. +- Fixed issue where tailable cursor would not retry even though cursor was still alive. +- Disabled exhaust flag support to avoid issues where users could easily write code that would cause memory to run out. +- Handle the case where the first command result document returns an empty list of documents but a live cursor. +- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options for kerberos. + +1.3.2 2016-02-09 +---------------- +- Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +- Ensure RequestId can never be larger than Max Number integer size. + +1.3.1 2016-02-05 +---------------- +- Removed annoying missing Kerberos error (NODE-654). + +1.3.0 2016-02-03 +---------------- +- Added raw support for the command function on topologies. +- Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +- Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +- Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +- NODE-638, Cannot authenticate database user with utf-8 password. +- Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +- Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +- Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +- Switched to using Array.push instead of concat for use cases of a lot of documents. +- Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +- Added peer optional dependencies support using require_optional module. + +1.2.32 2016-01-12 +----------------- +- Bumped bson to V0.4.21 to allow using minor optimizations. + +1.2.31 2016-01-04 +----------------- +- Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +1.2.30 2015-12-23 +----------------- +- Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +- Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +1.2.29 2015-12-17 +----------------- +- Correctly emit close event when calling destroy on server topology. + +1.2.28 2015-12-13 +----------------- +- Backed out Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous) as it breaks node 0.10.x support. + +1.2.27 2015-12-13 +----------------- +- Added [options.checkServerIdentity=true] {boolean|function}. Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function, (Issue #29). +- Prevent Maximum call stack exceeded by calling all callbacks on nextTick, (Issue #64, https://github.com/iamruinous). +- State is not defined in mongos, (Issue #63, https://github.com/flyingfisher). +- Fixed corner case issue on exhaust cursors on pre 3.0.x MongoDB. + +1.2.26 2015-11-23 +----------------- +- Converted test suite to use mongodb-topology-manager. +- Upgraded bson library to V0.4.20. +- Minor fixes for 3.2 readPreferences. + +1.2.25 2015-11-23 +----------------- +- Correctly error out when passed a seedlist of non-valid server members. + +1.2.24 2015-11-20 +----------------- +- Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). +- $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + +1.2.23 2015-11-16 +----------------- +- ismaster runs against admin.$cmd instead of system.$cmd. + +1.2.22 2015-11-16 +----------------- +- Fixes to handle getMore command errors for MongoDB 3.2 +- Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +1.2.21 2015-11-07 +----------------- +- Hardened the checking for replicaset equality checks. +- OpReplay flag correctly set on Wire protocol query. +- Mongos load balancing added, introduced localThresholdMS to control the feature. +- Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +1.2.20 2015-10-28 +----------------- +- Fixed bug in arbiter connection capping code. +- NODE-599 correctly handle arrays of server tags in order of priority. +- Fix for 2.6 wire protocol handler related to readPreference handling. +- Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +- Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +1.2.19 2015-10-15 +----------------- +- Make batchSize always be > 0 for 3.2 wire protocol to make it work consistently with pre 3.2 servers. +- Locked to bson 0.4.19. + +1.2.18 2015-10-15 +----------------- +- Minor 3.2 fix for handling readPreferences on sharded commands. +- Minor fixes to correctly pass APM specification test suite. + +1.2.17 2015-10-08 +----------------- +- Connections to arbiters only maintain a single connection. + +1.2.15 2015-10-06 +----------------- +- Set slaveOk to true for getMore and killCursors commands. +- Don't swallow callback errors for 2.4 single server (Issue #49, https://github.com/vkarpov15). +- Apply toString('hex') to each buffer in an array when logging (Issue #48, https://github.com/nbrachet). + +1.2.14 2015-09-28 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 2015-09-18 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 2015-09-08 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 2015-08-31 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 2015-08-14 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 2015-08-05 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 2015-07-24 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 2015-07-16 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 2015-07-14 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 2015-07-14 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 2015-07-07 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 2015-06-26 +----------------- +- Minor bug fixes. + +1.2.2 2015-06-22 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 2015-06-17 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 2015-06-17 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 2015-05-31 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 2015-05-20 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 2015-05-19 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 2015-05-18 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 2015-05-17 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 2015-05-12 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 2015-05-12 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 2015-05-06 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 2015-04-24 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 2015-04-22 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 2015-04-15 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 2015-04-10 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 2015-03-26 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 2015-03-24 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 2015-03-21 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 2015-03-17 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 2015-03-16 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 2015-03-06 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 2015-03-04 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 2015-02-26 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 2015-02-24 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 2015-02-16 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 2015-02-02 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 2015-31-01 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 2015-21-01 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 2015-09-12 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 2014-18-12 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 2014-18-12 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 2014-17-12 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 2014-17-12 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 2014-01-12 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 2014-20-11 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 2014-14-11 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 2014-29-10 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 2014-24-10 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 2014-21-10 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 2014-07-10 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 2014-07-10 +---------------- +- Dependency issue solved + +1.0.0 2014-07-10 +---------------- +- Initial release of mongodb-core diff --git a/node_modules/mongodb-core/LICENSE b/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/node_modules/mongodb-core/README.md b/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..d8b9edd --- /dev/null +++ b/node_modules/mongodb-core/README.md @@ -0,0 +1,228 @@ +[![Build Status](https://secure.travis-ci.org/mongodb-js/mongodb-core.png)](http://travis-ci.org/mongodb-js/mongodb-core) +[![Coverage Status](https://coveralls.io/repos/github/mongodb-js/mongodb-core/badge.svg?branch=1.3)](https://coveralls.io/github/mongodb-js/mongodb-core?branch=1.3) + +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/mongodb-js/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/node_modules/mongodb-core/index.js b/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..a542d79 --- /dev/null +++ b/node_modules/mongodb-core/index.js @@ -0,0 +1,48 @@ +'use strict'; + +var BSON = require('bson'); +var require_optional = require('require_optional'); +const EJSON = require('./lib/utils').retrieveEJSON(); + +try { + // Attempt to grab the native BSON parser + var BSONNative = require_optional('bson-ext'); + // If we got the native parser, use it instead of the + // Javascript one + if (BSONNative) { + BSON = BSONNative; + } +} catch (err) {} // eslint-disable-line + +module.exports = { + // Errors + MongoError: require('./lib/error').MongoError, + MongoNetworkError: require('./lib/error').MongoNetworkError, + MongoParseError: require('./lib/error').MongoParseError, + MongoTimeoutError: require('./lib/error').MongoTimeoutError, + MongoWriteConcernError: require('./lib/error').MongoWriteConcernError, + mongoErrorContextSymbol: require('./lib/error').mongoErrorContextSymbol, + // Core + Connection: require('./lib/connection/connection'), + Server: require('./lib/topologies/server'), + ReplSet: require('./lib/topologies/replset'), + Mongos: require('./lib/topologies/mongos'), + Logger: require('./lib/connection/logger'), + Cursor: require('./lib/cursor'), + ReadPreference: require('./lib/topologies/read_preference'), + Sessions: require('./lib/sessions'), + BSON: BSON, + EJSON: EJSON, + // Raw operations + Query: require('./lib/connection/commands').Query, + // Auth mechanisms + defaultAuthProviders: require('./lib/auth/defaultAuthProviders').defaultAuthProviders, + MongoCR: require('./lib/auth/mongocr'), + X509: require('./lib/auth/x509'), + Plain: require('./lib/auth/plain'), + GSSAPI: require('./lib/auth/gssapi'), + ScramSHA1: require('./lib/auth/scram').ScramSHA1, + ScramSHA256: require('./lib/auth/scram').ScramSHA256, + // Utilities + parseConnectionString: require('./lib/uri_parser') +}; diff --git a/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js b/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js new file mode 100644 index 0000000..fc5f4c2 --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/defaultAuthProviders.js @@ -0,0 +1,29 @@ +'use strict'; + +const MongoCR = require('./mongocr'); +const X509 = require('./x509'); +const Plain = require('./plain'); +const GSSAPI = require('./gssapi'); +const SSPI = require('./sspi'); +const ScramSHA1 = require('./scram').ScramSHA1; +const ScramSHA256 = require('./scram').ScramSHA256; + +/** + * Returns the default authentication providers. + * + * @param {BSON} bson Bson definition + * @returns {Object} a mapping of auth names to auth types + */ +function defaultAuthProviders(bson) { + return { + mongocr: new MongoCR(bson), + x509: new X509(bson), + plain: new Plain(bson), + gssapi: new GSSAPI(bson), + sspi: new SSPI(bson), + 'scram-sha-1': new ScramSHA1(bson), + 'scram-sha-256': new ScramSHA256(bson) + }; +} + +module.exports = { defaultAuthProviders }; diff --git a/node_modules/mongodb-core/lib/auth/gssapi.js b/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..cfaab74 --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,381 @@ +'use strict'; + +const f = require('util').format; +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const retrieveKerberos = require('../utils').retrieveKerberos; + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + let kerberos; + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + + // TODO: remove this once we fix URI parsing + var gssapiServiceName = options['gssapiservicename'] || options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize( + self, + kerberos.processes.MongoAuthProcess, + db, + username, + password, + db, + gssapiServiceName, + server, + connection, + options, + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// +// Initialize step +var GSSAPIInitialize = function( + self, + MongoAuthProcess, + db, + username, + password, + authdb, + gssapiServiceName, + server, + connection, + options, + callback +) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + // Perform initialization + mongo_auth_process.init(username, password, function(err) { + if (err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if (err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build the sasl start command + var command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload: payload, + autoAuthorize: 1 + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if (err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + } + ); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + // Write the commmand on the connection + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback + ); + }); + } + ); +}; + +var MongoDBGSSAPIThirdStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + server, + connection, + callback +) { + // Build final command + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (err) return callback(err, false); + mongo_auth_process.transition(null, function(err) { + if (err) return callback(err, null); + callback(null, r); + }); + } + ); +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +GSSAPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + authStore[i].options, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/node_modules/mongodb-core/lib/auth/mongocr.js b/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..3f6a36c --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,214 @@ +'use strict'; + +var f = require('util').format, + crypto = require('crypto'), + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Write the commmand on the connection + server( + connection, + new Query( + self.bson, + f('%s.$cmd', db), + { + getnonce: 1 + }, + { + numberToSkip: 0, + numberToReturn: 1 + } + ), + function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if (err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + // Execute command + // Write the commmand on the connection + server( + connection, + new Query( + self.bson, + f('%s.$cmd', db), + { + authenticate: 1, + user: username, + nonce: nonce, + key: key + }, + { + numberToSkip: 0, + numberToReturn: 1 + } + ), + function(err, r) { + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + executeMongoCR(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +MongoCR.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; diff --git a/node_modules/mongodb-core/lib/auth/plain.js b/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..deaea59 --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,183 @@ +'use strict'; + +var f = require('util').format, + retrieveBSON = require('../connection/utils').retrieveBSON, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var BSON = retrieveBSON(), + Binary = BSON.Binary; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f('\x00%s\x00%s', username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + // Let's start the process + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +Plain.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; diff --git a/node_modules/mongodb-core/lib/auth/scram.js b/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..719c580 --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,442 @@ +'use strict'; + +var f = require('util').format, + crypto = require('crypto'), + retrieveBSON = require('../connection/utils').retrieveBSON, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +let saslprep; + +try { + saslprep = require('saslprep'); +} catch (e) { + // don't do anything; +} + +var BSON = retrieveBSON(), + Binary = BSON.Binary; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +var id = 0; + +/** + * Creates a new ScramSHA authentication mechanism + * @class + * @return {ScramSHA} A cursor instance + */ +var ScramSHA = function(bson, cryptoMethod) { + this.bson = bson; + this.authStore = []; + this.id = id++; + this.cryptoMethod = cryptoMethod || 'sha1'; +}; + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for (var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +}; + +var passwordDigest = function(username, password) { + if (typeof username !== 'string') throw new MongoError('username must be a string'); + if (typeof password !== 'string') throw new MongoError('password must be a string'); + if (password.length === 0) throw new MongoError('password cannot be empty'); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + return md5.digest('hex'); +}; + +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) a = Buffer.from(a); + if (!Buffer.isBuffer(b)) b = Buffer.from(b); + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method, text) { + return crypto + .createHash(method) + .update(text) + .digest(); +} + +function HMAC(method, key, text) { + return crypto + .createHmac(method, key) + .update(text) + .digest(); +} + +var _hiCache = {}; +var _hiCacheCount = 0; +var _hiCachePurge = function() { + _hiCache = {}; + _hiCacheCount = 0; +}; + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] !== undefined) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + const cryptoMethod = this.cryptoMethod; + let mechanism = 'SCRAM-SHA-1'; + let processedPassword; + + if (cryptoMethod === 'sha256') { + mechanism = 'SCRAM-SHA-256'; + + let saslprepFn = (server.s && server.s.saslprep) || saslprep; + + if (saslprepFn) { + processedPassword = saslprepFn(password); + } else { + console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); + processedPassword = password; + } + } else { + processedPassword = passwordDigest(username, password); + } + + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', '=3D').replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + const firstBare = Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce, 'utf8') + ]); + + // Build command structure + var cmd = { + saslStart: 1, + mechanism: mechanism, + payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), + autoAuthorize: 1 + }; + + // Handle the error + var handleError = function(err, r) { + if (err) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; + return false; + } else if (r.result['$err']) { + errorObject = r.result; + return false; + } else if (r.result['errmsg']) { + errorObject = r.result; + return false; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true; + }; + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if (_count === 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if (_count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using scram')); + return callback(errorObject, false); + } + }; + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r); + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Do we have an error, handle it + if (handleError(err, r) === false) { + count = count - 1; + + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using scram')); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()); + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f('c=biws,r=%s', rnonce); + var saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + if (iterations && iterations < 4096) { + const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); + return callback(error, false); + } + + // Create the client key + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + + // Create the stored key + const storedKey = H(cryptoMethod, clientKey); + + // Create the authentication message + const authMessage = [ + firstBare, + r.result.payload.value().toString('base64'), + withoutProof + ].join(','); + + // Create client signature + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + + // Create client proof + const clientProof = f('p=%s', xor(clientKey, clientSignature)); + + // Create client final + const clientFinal = [withoutProof, clientProof].join(','); + + // Create continue message + const cmd = { + saslContinue: 1, + conversationId: r.result.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + // + // Execute sasl continue + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + if (r && r.result.done === false) { + var cmd = { + saslContinue: 1, + conversationId: r.result.conversationId, + payload: Buffer.alloc(0) + }; + + // Write the commmand on the connection + server( + connection, + new Query(self.bson, f('%s.$cmd', db), cmd, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + handleEnd(err, r); + } + ); + } else { + handleEnd(err, r); + } + } + ); + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + executeScram(_connection); + }); + }; + + // For each connection we need to authenticate + while (connections.length > 0) { + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +ScramSHA.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + // No connections + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +class ScramSHA1 extends ScramSHA { + constructor(bson) { + super(bson, 'sha1'); + } +} + +class ScramSHA256 extends ScramSHA { + constructor(bson) { + super(bson, 'sha256'); + } +} + +module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/node_modules/mongodb-core/lib/auth/sspi.js b/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..61ff48d --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,262 @@ +'use strict'; + +const f = require('util').format; +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const retrieveKerberos = require('../utils').retrieveKerberos; + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, connections, db, username, password, options, callback) { + var self = this; + let kerberos; + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate( + self, + kerberos.processes.MongoAuthProcess, + username, + password, + gssapiServiceName, + server, + connection, + options, + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r && typeof r === 'object' && r.result['$err']) { + errorObject = r.result; + } else if (r && typeof r === 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +function SSIPAuthenticate( + self, + MongoAuthProcess, + username, + password, + gssapiServiceName, + server, + connection, + options, + callback +) { + const authProcess = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + function authCommand(command, authCb) { + const query = new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }); + + server(connection, query, authCb); + } + + authProcess.init(username, password, err => { + if (err) return callback(err, false); + + authProcess.transition('', (err, payload) => { + if (err) return callback(err, false); + + const command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; + + authCommand(command, (err, result) => { + if (err) return callback(err, false); + const doc = result.result; + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, result) => { + if (err) return callback(err, false); + const doc = result.result; + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, response) => { + if (err) return callback(err, false); + + authProcess.transition(null, err => { + if (err) return callback(err, null); + callback(null, response); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +SSPI.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + authStore[i].options, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; diff --git a/node_modules/mongodb-core/lib/auth/x509.js b/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..e7c4bd8 --- /dev/null +++ b/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,179 @@ +'use strict'; + +var f = require('util').format, + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError; + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +}; + +AuthSession.prototype.equal = function(session) { + return ( + session.db === this.db && + session.username === this.username && + session.password === this.password + ); +}; + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function(bson) { + this.bson = bson; + this.authStore = []; +}; + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, connections, db, username, password, callback) { + var self = this; + // Total connections + var count = connections.length; + if (count === 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var errorObject = null; + + // For each connection we need to authenticate + while (connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1, + mechanism: 'MONGODB-X509' + }; + + // Add username if specified + if (username) { + command.user = username; + } + + // Let's start the process + server( + connection, + new Query(self.bson, '$external.$cmd', command, { + numberToSkip: 0, + numberToReturn: 1 + }), + function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = err; + } else if (r.result['$err']) { + errorObject = r.result; + } else if (r.result['errmsg']) { + errorObject = r.result; + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if (count === 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if (count === 0) { + if (errorObject == null) + errorObject = new MongoError(f('failed to authenticate using mongocr')); + callback(errorObject, false); + } + } + ); + }; + + var _execute = function(_connection) { + process.nextTick(function() { + execute(_connection); + }); + }; + + _execute(connections.shift()); + } +}; + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for (var i = 0; i < authStore.length; i++) { + if (authStore[i].equal(session)) { + found = true; + break; + } + } + + if (!found) authStore.push(session); +}; + +/** + * Remove authStore credentials + * @method + * @param {string} db Name of database we are removing authStore details about + * @return {object} + */ +X509.prototype.logout = function(dbName) { + this.authStore = this.authStore.filter(function(x) { + return x.db !== dbName; + }); +}; + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {[]Connections} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, connections, callback) { + var authStore = this.authStore.slice(0); + var count = authStore.length; + if (count === 0) return callback(null, null); + // Iterate over all the auth details stored + for (var i = 0; i < authStore.length; i++) { + this.auth( + server, + connections, + authStore[i].db, + authStore[i].username, + authStore[i].password, + function(err) { + count = count - 1; + // Done re-authenticating + if (count === 0) { + callback(err, null); + } + } + ); + } +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; diff --git a/node_modules/mongodb-core/lib/connection/apm.js b/node_modules/mongodb-core/lib/connection/apm.js new file mode 100644 index 0000000..2fbab84 --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/apm.js @@ -0,0 +1,229 @@ +'use strict'; +const KillCursor = require('../connection/commands').KillCursor; +const GetMore = require('../connection/commands').GetMore; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +// helper methods +const extractCommandName = command => Object.keys(command)[0]; +const namespace = command => command.ns; +const databaseName = command => command.ns.split('.')[0]; +const collectionName = command => command.ns.split('.')[1]; +const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; +const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); + +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldsSelector: 'projection' +}; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; + +/** + * Extract the actual command from the query, possibly upconverting if it's a legacy + * format + * + * @param {Object} command the command + */ +const extractCommand = command => { + if (command instanceof GetMore) { + return { + getMore: command.cursorId, + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: command.cursorIds + }; + } + + if (command.query && command.query.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // upconvert legacy command + result = Object.assign({}, command.query.$query); + } else { + // upconvert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (typeof command.query[key] !== 'undefined') + result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + if (typeof command.options[key] !== 'undefined') + result[LEGACY_FIND_OPTIONS_MAP[key]] = command.options[key]; + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) result[key] = command[key]; + }); + + if (typeof command.pre32Limit !== 'undefined') { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + + return result; + } + + return command.query ? command.query : command; +}; + +const extractReply = (command, reply) => { + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + nextBatch: reply.message.documents + } + }; + } + + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + // is this a legacy find command? + if (command.query && typeof command.query.$query !== 'undefined') { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + firstBatch: reply.message.documents + } + }; + } + + return reply.result; +}; + +/** An event indicating the start of a given command */ +class CommandStartedEvent { + /** + * Create a started event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + */ + constructor(pool, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + // NOTE: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + Object.assign(this, { + command: cmd, + databaseName: databaseName(command), + commandName, + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the success of a given command */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {Object} reply the reply for this command from the server + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + reply: maybeRedact(commandName, extractReply(command, reply)), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the failure of a given command */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {MongoError|Object} error the generated error or a server error response + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + failure: maybeRedact(commandName, error), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +module.exports = { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +}; diff --git a/node_modules/mongodb-core/lib/connection/command_result.js b/node_modules/mongodb-core/lib/connection/command_result.js new file mode 100644 index 0000000..be4eb52 --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/command_result.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +}; + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +}; + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +}; + +module.exports = CommandResult; diff --git a/node_modules/mongodb-core/lib/connection/commands.js b/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..6015713 --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,549 @@ +'use strict'; + +var retrieveBSON = require('./utils').retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; +const MongoError = require('../error').MongoError; +const Buffer = require('safe-buffer').Buffer; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var opcodes = require('../wireprotocol/shared').opcodes; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if (ns == null) throw new Error('ns must be specified for query'); + if (query == null) throw new Error('query must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + throw new Error('namespace cannot contain a null character'); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +}; + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +}; + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(self.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; + header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; + header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; + header[index] = opcodes.OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +}; + +Query.getRequestId = function() { + return ++_requestId; +}; + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; + _buffer[index] = opcodes.OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +}; + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + var index = 0; + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +}; + +var Response = function(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; +}; + +Response.prototype.isParsed = function() { + return this.parsed; +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + var promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + var promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // + // Single document and documentsReturnedIn set + // + if (this.numberReturned === 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + if (doc instanceof Error) { + throw doc; + } + + if (doc.errmsg) { + throw new MongoError(doc.errmsg); + } + + if (!doc.cursor) { + throw new MongoError('Cursor not found'); + } + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = + typeof doc.cursor.id === 'number' ? Long.fromNumber(doc.cursor.id) : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true; + return; + } + + // + // Parse Body + // + for (var i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +}; + +module.exports = { + Query: Query, + GetMore: GetMore, + Response: Response, + KillCursor: KillCursor +}; diff --git a/node_modules/mongodb-core/lib/connection/connection.js b/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..71d461a --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,805 @@ +'use strict'; + +var inherits = require('util').inherits, + EventEmitter = require('events').EventEmitter, + net = require('net'), + tls = require('tls'), + crypto = require('crypto'), + f = require('util').format, + debugOptions = require('./utils').debugOptions, + parseHeader = require('../wireprotocol/shared').parseHeader, + decompress = require('../wireprotocol/compression').decompress, + Response = require('./commands').Response, + MongoNetworkError = require('../error').MongoNetworkError, + Logger = require('./logger'), + OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED, + MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE, + Buffer = require('safe-buffer').Buffer; + +var _id = 0; +var debugFields = [ + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'socketTimeout', + 'singleBufferSerializtion', + 'ssl', + 'ca', + 'crl', + 'cert', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'checkServerIdentity' +]; + +var connectionAccountingSpy = undefined; +var connectionAccounting = false; +var connections = {}; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.family=null] IP version for DNS lookup, passed down to Node's [`dns.lookup()` function](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback). If set to `6`, will only look for ipv6 addresses. + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(messageHandler, options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if (!options.bson) throw new Error('must pass in valid bson parser'); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || 1024 * 1024 * 16 * 4; + // Debug information + if (this.logger.isDebug()) + this.logger.debug( + f( + 'creating connection %s with options [%s]', + this.id, + JSON.stringify(debugOptions(debugFields, options)) + ) + ); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.family = typeof options.family === 'number' ? options.family : void 0; + this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + this.noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; + this.connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + + // Is the keepAliveInitialDelay > socketTimeout set it to half of socketTimeout + if (this.keepAliveInitialDelay > this.socketTimeout) { + this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); + } + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('/') !== -1; + + // Serialize commands using function + this.singleBufferSerializtion = + typeof options.singleBufferSerializtion === 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.crl = options.crl || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ciphers = options.ciphers || null; + this.ecdhCurve = options.ecdhCurve || null; + this.ssl = typeof options.ssl === 'boolean' ? options.ssl : false; + this.rejectUnauthorized = + typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; + this.checkServerIdentity = + typeof options.checkServerIdentity === 'boolean' || + typeof options.checkServerIdentity === 'function' + ? options.checkServerIdentity + : true; + + // If ssl not enabled + if (!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false + }; + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; + + // Create hash method + var hash = crypto.createHash('sha1'); + hash.update(f('%s:%s', this.host, this.port)); + + // Create a hash name + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; +}; + +inherits(Connection, EventEmitter); + +Connection.prototype.setSocketTimeout = function(value) { + if (this.connection) { + this.connection.setTimeout(value); + } +}; + +Connection.prototype.resetSocketTimeout = function() { + if (this.connection) { + this.connection.setTimeout(this.socketTimeout); + } +}; + +Connection.enableConnectionAccounting = function(spy) { + if (spy) { + connectionAccountingSpy = spy; + } + + connectionAccounting = true; + connections = {}; +}; + +Connection.disableConnectionAccounting = function() { + connectionAccounting = false; + connectionAccountingSpy = undefined; +}; + +Connection.connections = function() { + return connections; +}; + +function deleteConnection(id) { + // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) + delete connections[id]; + + if (connectionAccountingSpy) { + connectionAccountingSpy.deleteConnection(id); + } +} + +function addConnection(id, connection) { + // console.log("=== added connection " + id + " :: " + connection.port) + connections[id] = connection; + + if (connectionAccountingSpy) { + connectionAccountingSpy.addConnection(id, connection); + } +} + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug( + f( + 'connection %s for [%s:%s] errored out with [%s]', + self.id, + self.host, + self.port, + JSON.stringify(err) + ) + ); + // Emit the error + if (self.listeners('error').length > 0) self.emit('error', new MongoNetworkError(err), self); + }; +}; + +var timeoutHandler = function(self) { + return function() { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit( + 'timeout', + new MongoNetworkError(f('connection %s to %s:%s timed out', self.id, self.host, self.port)), + self + ); + }; +}; + +var closeHandler = function(self) { + return function(hadError) { + if (connectionAccounting) deleteConnection(self.id); + // Debug information + if (self.logger.isDebug()) + self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + + // Emit close event + if (!hadError) { + self.emit( + 'close', + new MongoNetworkError(f('connection %s to %s:%s closed', self.id, self.host, self.port)), + self + ); + } + }; +}; + +// Handle a message once it is received +var emitMessageHandler = function(self, message) { + var msgHeader = parseHeader(message); + if (msgHeader.opCode === OP_COMPRESSED) { + msgHeader.fromCompressed = true; + var index = MESSAGE_HEADER_SIZE; + msgHeader.opCode = message.readInt32LE(index); + index += 4; + msgHeader.length = message.readInt32LE(index); + index += 4; + var compressorID = message[index]; + index++; + decompress(compressorID, message.slice(index), function(err, decompressedMsgBody) { + if (err) { + throw err; + } + if (decompressedMsgBody.length !== msgHeader.length) { + throw new Error( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ); + } + self.messageHandler( + new Response(self.bson, message, msgHeader, decompressedMsgBody, self.responseOptions), + self + ); + }); + } else { + self.messageHandler( + new Response( + self.bson, + message, + msgHeader, + message.slice(MESSAGE_HEADER_SIZE), + self.responseOptions + ), + self + ); + } +}; + +var dataHandler = function(self) { + 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 = Buffer.alloc(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; + + emitMessageHandler(self, emitBuffer); + } catch (err) { + var errorObject = { + err: 'socketHandler', + trace: err, + bin: self.buffer, + parseState: { + sizeOfMessage: self.sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer + } + }; + // 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 = Buffer.alloc(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 = Buffer.alloc(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 = Buffer.alloc(0); + } + } else { + if (data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); + // If we have a negative sizeOfMessage emit error and return + if (sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = { + err: 'socketHandler', + trace: '', + bin: self.buffer, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer + } + }; + // 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.maxBsonMessageSize && + sizeOfMessage > data.length + ) { + self.buffer = Buffer.alloc(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 = Buffer.alloc(0); + } else if ( + sizeOfMessage > 4 && + sizeOfMessage < self.maxBsonMessageSize && + sizeOfMessage === data.length + ) { + try { + emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + // Emit the message + emitMessageHandler(self, emitBuffer); + } catch (err) { + self.emit('parseError', err, self); + } + } else if (sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + errorObject = { + err: 'socketHandler', + trace: null, + bin: data, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: 0, + buffer: null, + stubBuffer: null + } + }; + // 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 = Buffer.alloc(0); + } else { + 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 + emitMessageHandler(self, emitBuffer); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = Buffer.alloc(data.length); + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = Buffer.alloc(0); + } + } + } + } + }; +}; + +// List of socket level valid ssl options +var legalSslSocketOptions = [ + 'pfx', + 'key', + 'passphrase', + 'cert', + 'ca', + 'ciphers', + 'NPNProtocols', + 'ALPNProtocols', + 'servername', + 'ecdhCurve', + 'secureProtocol', + 'secureContext', + 'session', + 'minDHSize' +]; + +function merge(options1, options2) { + // Merge in any allowed ssl options + for (var name in options2) { + if (options2[name] != null && legalSslSocketOptions.indexOf(name) !== -1) { + options1[name] = options2[name]; + } + } +} + +function makeSSLConnection(self, _options) { + let sslOptions = { + socket: self.connection, + rejectUnauthorized: self.rejectUnauthorized + }; + + // Merge in options + merge(sslOptions, self.options); + merge(sslOptions, _options); + + // Set options for ssl + if (self.ca) sslOptions.ca = self.ca; + if (self.crl) sslOptions.crl = self.crl; + if (self.cert) sslOptions.cert = self.cert; + if (self.key) sslOptions.key = self.key; + if (self.passphrase) sslOptions.passphrase = self.passphrase; + + // Override checkServerIdentity behavior + if (self.checkServerIdentity === false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + sslOptions.checkServerIdentity = function() { + return undefined; + }; + } else if (typeof self.checkServerIdentity === 'function') { + sslOptions.checkServerIdentity = self.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if (sslOptions.servername == null) { + sslOptions.servername = self.host; + } + + // Attempt SSL connection + const connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if (connection.authorizationError && self.rejectUnauthorized) { + return self.emit('error', connection.authorizationError, self, { ssl: true }); + } + + // Set socket timeout instead of connection timeout + connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + + // Set the options for the connection + connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + connection.setTimeout(self.connectionTimeout); + connection.setNoDelay(self.noDelay); + + return connection; +} + +function makeUnsecureConnection(self, family) { + // Create new connection instance + let connection_options; + if (self.domainSocket) { + connection_options = { path: self.host }; + } else { + connection_options = { port: self.port, host: self.host }; + connection_options.family = family; + } + + const connection = net.createConnection(connection_options); + + // Set the options for the connection + connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + connection.setTimeout(self.connectionTimeout); + connection.setNoDelay(self.noDelay); + + connection.once('connect', function() { + // Set socket timeout instead of connection timeout + connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + + return connection; +} + +function doConnect(self, family, _options, _errorHandler) { + self.connection = self.ssl + ? makeSSLConnection(self, _options) + : makeUnsecureConnection(self, family); + + // Add handlers for events + self.connection.once('error', _errorHandler); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + _options = _options || {}; + // Set the connections + if (connectionAccounting) addConnection(this.id, this); + // Check if we are overriding the promoteLongs + if (typeof _options.promoteLongs === 'boolean') { + this.responseOptions.promoteLongs = _options.promoteLongs; + this.responseOptions.promoteValues = _options.promoteValues; + this.responseOptions.promoteBuffers = _options.promoteBuffers; + } + + const _errorHandler = errorHandler(this); + + if (this.family !== void 0) { + return doConnect(this, this.family, _options, _errorHandler); + } + + return doConnect(this, 6, _options, err => { + if (this.logger.isDebug()) { + this.logger.debug( + f( + 'connection %s for [%s:%s] errored out with [%s]', + this.id, + this.host, + this.port, + JSON.stringify(err) + ) + ); + } + + // clean up existing event handlers + this.connection.removeAllListeners('error'); + this.connection.removeAllListeners('timeout'); + this.connection.removeAllListeners('close'); + this.connection.removeAllListeners('data'); + this.connection = undefined; + + return doConnect(this, 4, _options, _errorHandler); + }); +}; + +/** + * Unref this connection + * @method + * @return {boolean} + */ +Connection.prototype.unref = function() { + if (this.connection) this.connection.unref(); + else { + var self = this; + this.once('connect', function() { + self.connection.unref(); + }); + } +}; + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + // Set the connections + if (connectionAccounting) deleteConnection(this.id); + if (this.connection) { + // Catch posssible exception thrown by node 0.10.x + try { + this.connection.end(); + } catch (err) {} // eslint-disable-line + // Destroy connection + this.connection.destroy(); + } + + this.destroyed = true; +}; + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + var i; + // Debug Log + if (this.logger.isDebug()) { + if (!Array.isArray(buffer)) { + this.logger.debug( + f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port) + ); + } else { + for (i = 0; i < buffer.length; i++) + this.logger.debug( + f('writing buffer [%s] to %s:%s', buffer[i].toString('hex'), this.host, this.port) + ); + } + } + + // Double check that the connection is not destroyed + if (this.connection.destroyed === false) { + // Write out the command + if (!Array.isArray(buffer)) { + this.connection.write(buffer, 'binary'); + return true; + } + + // Iterate over all buffers and write them in order to the socket + for (i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); + return true; + } + + // Connection is destroyed return write failed + return false; +}; + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return '' + this.id; +}; + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return { id: this.id, host: this.host, port: this.port }; +}; + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if (this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/node_modules/mongodb-core/lib/connection/logger.js b/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..eb11e43 --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,246 @@ +'use strict'; + +var f = require('util').format, + MongoError = require('../error').MongoError; + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if (!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if (options.logger) { + currentLogger = options.logger; + } else if (currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if (filteredClasses[this.className] == null) classFilters[this.className] = true; +}; + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}; + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +(Logger.prototype.warn = function(message, object) { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}), + /** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.info = function(message, object) { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.error = function(message, object) { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Is the logger set at info level + * @method + * @return {boolean} + */ + (Logger.prototype.isInfo = function() { + return level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isError = function() { + return level === 'error' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isWarn = function() { + return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at debug level + * @method + * @return {boolean} + */ + (Logger.prototype.isDebug = function() { + return level === 'debug'; + }); + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +}; + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +}; + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); + currentLogger = logger; +}; + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +}; + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { + throw new Error(f('%s is an illegal logging level', _level)); + } + + level = _level; +}; + +module.exports = Logger; diff --git a/node_modules/mongodb-core/lib/connection/pool.js b/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..02458be --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,1657 @@ +'use strict'; + +const inherits = require('util').inherits; +const EventEmitter = require('events').EventEmitter; +const Connection = require('./connection'); +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const MongoWriteConcernError = require('../error').MongoWriteConcernError; +const Logger = require('./logger'); +const f = require('util').format; +const Query = require('./commands').Query; +const CommandResult = require('./command_result'); +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const opcodes = require('../wireprotocol/shared').opcodes; +const compress = require('../wireprotocol/compression').compress; +const compressorIDs = require('../wireprotocol/compression').compressorIDs; +const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; +const resolveClusterTime = require('../topologies/shared').resolveClusterTime; +const apm = require('./apm'); +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; +const Buffer = require('safe-buffer').Buffer; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +function hasSessionSupport(topology) { + if (topology == null) return false; + return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; +} + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Max server connection pool size + * @param {number} [options.minSize=0] Minimum server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(topology, options) { + // Add event listener + EventEmitter.call(this); + + // Store topology for later use + this.topology = topology; + + // Add the options + this.options = Object.assign( + { + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // Pool default min size + minSize: 0, + // socket settings + connectionTimeout: 30000, + socketTimeout: 360000, + keepAlive: true, + keepAliveInitialDelay: 300000, + noDelay: true, + // SSL Settings + ssl: false, + checkServerIdentity: true, + ca: null, + crl: null, + cert: null, + key: null, + passPhrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false + }, + options + ); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + // No bson parser passed in + if ( + !options.bson || + (options.bson && + (typeof options.bson.serialize !== 'function' || + typeof options.bson.deserialize !== 'function')) + ) { + throw new Error('must pass in valid bson parser'); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Pool state + this.state = DISCONNECTED; + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = []; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(options.bson); + + // Contains the reconnect connection + this.reconnectConnection = null; + + // Are we currently authenticating + this.authenticating = false; + this.loggingout = false; + this.nonAuthenticatedConnections = []; + this.authenticatingTimestamp = null; + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; +}; + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable: true, + get: function() { + return this.options.size; + } +}); + +Object.defineProperty(Pool.prototype, 'minSize', { + enumerable: true, + get: function() { + return this.options.minSize; + } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable: true, + get: function() { + return this.options.connectionTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable: true, + get: function() { + return this.options.socketTimeout; + } +}); + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING], + destroying: [DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.emit('stateChanged', self.state, newState); + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +function authenticate(pool, auth, connection, cb) { + if (auth[0] === undefined) return cb(null); + // We need to authenticate the server + var mechanism = auth[0]; + var db = auth[1]; + // Validate if the mechanism exists + if (!pool.authProviders[mechanism]) { + throw new MongoError(f('authMechanism %s not supported', mechanism)); + } + + // Get the provider + var provider = pool.authProviders[mechanism]; + + // Authenticate using the provided mechanism + provider.auth.apply(provider, [write(pool), [connection], db].concat(auth.slice(2)).concat([cb])); +} + +// The write function used by the authentication mechanism (bypasses external) +function write(self) { + return function(connection, command, callback) { + // Get the raw buffer + // Ensure we stop auth if pool was destroyed + if (self.state === DESTROYED || self.state === DESTROYING) { + return callback(new MongoError('pool destroyed')); + } + + // Set the connection workItem callback + connection.workItems.push({ + cb: callback, + command: true, + requestId: command.requestId + }); + + // Write the buffer out to the connection + connection.write(command.toBin()); + }; +} + +function reauthenticate(pool, connection, cb) { + // Authenticate + function authenticateAgainstProvider(pool, connection, providers, cb) { + // Finished re-authenticating against providers + if (providers.length === 0) return cb(); + // Get the provider name + var provider = pool.authProviders[providers.pop()]; + + // Auth provider + provider.reauthenticate(write(pool), [connection], function(err) { + // We got an error return immediately + if (err) return cb(err); + // Continue authenticating the connection + authenticateAgainstProvider(pool, connection, providers, cb); + }); + } + + // Start re-authenticating process + authenticateAgainstProvider(pool, connection, Object.keys(pool.authProviders), cb); +} + +function connectionFailureHandler(self, event) { + return function(err) { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + + // Remove the connection + removeConnection(self, this); + + // Flush all work Items on this connection + while (this.workItems.length > 0) { + var workItem = this.workItems.shift(); + if (workItem.cb) workItem.cb(err); + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if (event === 'timeout') { + self.numberOfConsecutiveTimeouts = self.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if (self.numberOfConsecutiveTimeouts > self.options.reconnectTries) { + self.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + self.destroy(true); + // Emit close event + return self.emit('close', self); + } + } + + // No more socket available propegate the event + if (self.socketCount() === 0) { + if (self.state !== DESTROYED && self.state !== DESTROYING) { + stateTransition(self, DISCONNECTED); + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event === 'error' ? 'close' : event; + self.emit(event, err); + } + + // Start reconnection attempts + if (!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + + // Do we need to do anything to maintain the minimum pool size + const totalConnections = + self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length; + + if (totalConnections < self.minSize) { + _createConnection(self); + } + }; +} + +function attemptReconnect(self) { + return function() { + self.emit('attemptReconnect', self); + if (self.state === DESTROYED || self.state === DESTROYING) return; + + // We are connected do not try again + if (self.isConnected()) { + self.reconnectId = null; + return; + } + + // If we have failure schedule a retry + function _connectionFailureHandler(self) { + return function() { + if (this._connectionFailHandled) return; + this._connectionFailHandled = true; + // Destroy the connection + this.destroy(); + // Count down the number of reconnects + self.retriesLeft = self.retriesLeft - 1; + // How many retries are left + if (self.retriesLeft <= 0) { + // Destroy the instance + self.destroy(); + // Emit close event + self.emit( + 'reconnectFailed', + new MongoNetworkError( + f( + 'failed to reconnect after %s attempts with interval %s ms', + self.options.reconnectTries, + self.options.reconnectInterval + ) + ) + ); + } else { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + }; + } + + // Got a connect handler + function _connectHandler(self) { + return function() { + // Assign + var connection = this; + + // Pool destroyed stop the connection + if (self.state === DESTROYED || self.state === DESTROYING) { + return connection.destroy(); + } + + // Clear out all handlers + handlers.forEach(function(event) { + connection.removeAllListeners(event); + }); + + // Reset reconnect id + self.reconnectId = null; + + // Apply pool connection handlers + connection.on('error', connectionFailureHandler(self, 'error')); + connection.on('close', connectionFailureHandler(self, 'close')); + connection.on('timeout', connectionFailureHandler(self, 'timeout')); + connection.on('parseError', connectionFailureHandler(self, 'parseError')); + + // Apply any auth to the connection + reauthenticate(self, this, function() { + // Reset retries + self.retriesLeft = self.options.reconnectTries; + // Push to available connections + self.availableConnections.push(connection); + // Set the reconnectConnection to null + self.reconnectConnection = null; + // Emit reconnect event + self.emit('reconnect', self); + // Trigger execute to start everything up again + _execute(self)(); + }); + }; + } + + // Create a connection + self.reconnectConnection = new Connection(messageHandler(self), self.options); + // Add handlers + self.reconnectConnection.on('close', _connectionFailureHandler(self, 'close')); + self.reconnectConnection.on('error', _connectionFailureHandler(self, 'error')); + self.reconnectConnection.on('timeout', _connectionFailureHandler(self, 'timeout')); + self.reconnectConnection.on('parseError', _connectionFailureHandler(self, 'parseError')); + // On connection + self.reconnectConnection.on('connect', _connectHandler(self)); + // Attempt connection + self.reconnectConnection.connect(); + }; +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if (index !== -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for (var i = 0; i < connection.workItems.length; i++) { + if (connection.workItems[i].requestId === message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if (workItem && workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'message [%s] received from %s:%s', + message.raw.toString('hex'), + self.options.host, + self.options.port + ) + ); + } + + // Authenticate any straggler connections + function authenticateStragglers(self, connection, callback) { + // Get any non authenticated connections + var connections = self.nonAuthenticatedConnections.slice(0); + var nonAuthenticatedConnections = self.nonAuthenticatedConnections; + self.nonAuthenticatedConnections = []; + + // Establish if the connection need to be authenticated + // Add to authentication list if + // 1. we were in an authentication process when the operation was executed + // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened + if ( + connection.workItems.length === 1 && + (connection.workItems[0].authenticating === true || + (typeof connection.workItems[0].authenticatingTimestamp === 'number' && + connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) + ) { + // Add connection to the list + connections.push(connection); + } + + // No connections need to be re-authenticated + if (connections.length === 0) { + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Finish + return callback(); + } + + // Apply re-authentication to all connections before releasing back to pool + var connectionCount = connections.length; + // Authenticate all connections + for (var i = 0; i < connectionCount; i++) { + reauthenticate(self, connections[i], function() { + connectionCount = connectionCount - 1; + + if (connectionCount === 0) { + // Put non authenticated connections in available connections + self.availableConnections = self.availableConnections.concat( + nonAuthenticatedConnections + ); + // Release the connection back to the pool + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + // Return + callback(); + } + }); + } + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if (!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + authenticateStragglers(self, connection, function() { + // Keep executing, ensure current message handler does not stop execution + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if (workItem && !workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch (err) { + return handleOperationCallback(self, workItem.cb, new MongoError(err)); + } + + // Look for clusterTime, and operationTime and update them if necessary + if (message.documents[0]) { + if (message.documents[0].$clusterTime) { + const $clusterTime = message.documents[0].$clusterTime; + self.topology.clusterTime = $clusterTime; + + if (workItem.session != null) { + resolveClusterTime(workItem.session, $clusterTime); + } + } + + if ( + message.documents[0].operationTime && + workItem.session && + workItem.session.supports.causalConsistency + ) { + workItem.session.advanceOperationTime(message.documents[0].operationTime); + } + } + + // Establish if we have an error + if (workItem.command && message.documents[0]) { + const responseDoc = message.documents[0]; + if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { + return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); + } + + if (responseDoc.writeConcernError) { + const err = + responseDoc.ok === 1 + ? new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc) + : new MongoWriteConcernError(responseDoc.writeConcernError); + return handleOperationCallback(self, workItem.cb, err); + } + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback( + self, + workItem.cb, + null, + new CommandResult( + workItem.fullResult ? message : message.documents[0], + connection, + message + ) + ); + } + }); + }; +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + this.inUseConnections.length; + // + this.connectingConnections.length; +}; + +/** + * Return all pool connections + * @method + * @return {Connection[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections.concat(this.inUseConnections).concat(this.connectingConnections); +}; + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +}; + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if (this.state === DESTROYED || this.state === DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections.concat(this.inUseConnections); + + // Check if we have any connected connections + for (var i = 0; i < connections.length; i++) { + if (connections[i].isConnected()) return true; + } + + // Might be authenticating, but we are still connected + if (connections.length === 0 && this.authenticating) { + return true; + } + + // Not connected + return false; +}; + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state === DESTROYED || this.state === DESTROYING; +}; + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state === DISCONNECTED; +}; + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function() { + if (this.state !== DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + var self = this; + // Transition to connecting state + stateTransition(this, CONNECTING); + // Create an array of the arguments + var args = Array.prototype.slice.call(arguments, 0); + // Create a connection + var connection = new Connection(messageHandler(self), this.options); + // Add to list of connections + this.connectingConnections.push(connection); + // Add listeners to the connection + connection.once('connect', function(connection) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // If we are in a topology, delegate the auth to it + // This is to avoid issues where we would auth against an + // arbiter + if (self.options.inTopology) { + // Set connected mode + stateTransition(self, CONNECTED); + + // Move the active connection + moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); + + // Emit the connect event + return self.emit('connect', self); + } + + // Apply any store credentials + reauthenticate(self, connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // We have an error emit it + if (err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + + // Authenticate + authenticate(self, args, connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) return self.destroy(); + + // We have an error emit it + if (err) { + // Destroy the pool + self.destroy(); + // Emit the error + return self.emit('error', err); + } + // Set connected mode + stateTransition(self, CONNECTED); + + // Move the active connection + moveConnectionBetween(connection, self.connectingConnections, self.availableConnections); + + // if we have a minPoolSize, create a connection + if (self.minSize) { + for (let i = 0; i < self.minSize; i++) _createConnection(self); + } + + // Emit the connect event + self.emit('connect', self); + }); + }); + }); + + // Add error handlers + connection.once('error', connectionFailureHandler(this, 'error')); + connection.once('close', connectionFailureHandler(this, 'close')); + connection.once('timeout', connectionFailureHandler(this, 'timeout')); + connection.once('parseError', connectionFailureHandler(this, 'parseError')); + + try { + connection.connect(); + } catch (err) { + // SSL or something threw on connect + process.nextTick(function() { + self.emit('error', err); + }); + } +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(mechanism) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + + // If we don't have the mechanism fail + if (self.authProviders[mechanism] == null && mechanism !== 'default') { + throw new MongoError(f('auth provider %s does not exist', mechanism)); + } + + // Signal that we are authenticating a new set of credentials + this.authenticating = true; + this.authenticatingTimestamp = new Date().getTime(); + + // Authenticate all live connections + function authenticateLiveConnections(self, args, cb) { + // Get the current viable connections + var connections = self.allConnections(); + // Allow nothing else to use the connections while we authenticate them + self.availableConnections = []; + self.inUseConnections = []; + self.connectingConnections = []; + + var connectionsCount = connections.length; + var error = null; + // No connections available, return + if (connectionsCount === 0) { + self.authenticating = false; + return callback(null); + } + + // Authenticate the connections + for (var i = 0; i < connections.length; i++) { + authenticate(self, args, connections[i], function(err, result) { + connectionsCount = connectionsCount - 1; + + // Store the error + if (err) error = err; + + // Processed all connections + if (connectionsCount === 0) { + // Auth finished + self.authenticating = false; + // Add the connections back to available connections + self.availableConnections = self.availableConnections.concat(connections); + // We had an error, return it + if (error) { + // Log the error + if (self.logger.isError()) { + self.logger.error( + f( + '[%s] failed to authenticate against server %s:%s', + self.id, + self.options.host, + self.options.port + ) + ); + } + + return cb(error, result); + } + cb(null, result); + } + }); + } + } + + // Wait for a logout in process to happen + function waitForLogout(self, cb) { + if (!self.loggingout) return cb(); + setTimeout(function() { + waitForLogout(self, cb); + }, 1); + } + + // Wait for loggout to finish + waitForLogout(self, function() { + // Authenticate all live connections + authenticateLiveConnections(self, args, function(err, result) { + // Credentials correctly stored in auth provider if successful + // Any new connections will now reauthenticate correctly + self.authenticating = false; + // Return after authentication connections + callback(err, result); + }); + }); +}; + +/** + * Logout all users against a database + * @method + * @param {string} dbName The database name + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + var self = this; + if (typeof dbName !== 'string') { + throw new MongoError('logout method requires a db name as first argument'); + } + + if (typeof callback !== 'function') { + throw new MongoError('logout method requires a callback'); + } + + // Indicate logout in process + this.loggingout = true; + + // Get all relevant connections + var connections = self.availableConnections.concat(self.inUseConnections); + var count = connections.length; + // Store any error + var error = null; + + // Send logout command over all the connections + for (var i = 0; i < connections.length; i++) { + write(self)( + connections[i], + new Query( + this.options.bson, + f('%s.$cmd', dbName), + { logout: 1 }, + { numberToSkip: 0, numberToReturn: 1 } + ), + function(err) { + count = count - 1; + if (err) error = err; + + if (count === 0) { + self.loggingout = false; + callback(error); + } + } + ); + } +}; + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections + .concat(this.inUseConnections) + .concat(this.connectingConnections); + connections.forEach(function(c) { + c.unref(); + }); +}; + +// Events +var events = ['error', 'close', 'timeout', 'parseError', 'connect']; + +// Destroy the connections +function destroy(self, connections) { + // Destroy all connections + connections.forEach(function(c) { + // Remove all listeners + for (var i = 0; i < events.length; i++) { + c.removeAllListeners(events[i]); + } + // Destroy connection + c.destroy(); + }); + + // Zero out all connections + self.inUseConnections = []; + self.availableConnections = []; + self.nonAuthenticatedConnections = []; + self.connectingConnections = []; + + // Set state to destroyed + stateTransition(self, DESTROYED); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force) { + var self = this; + // Do not try again if the pool is already dead + if (this.state === DESTROYED || self.state === DESTROYING) return; + // Set state to destroyed + stateTransition(this, DESTROYING); + + // Are we force closing + if (force) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + + // Flush any remaining work items with + // an error + while (self.queue.length > 0) { + var workItem = self.queue.shift(); + if (typeof workItem.cb === 'function') { + workItem.cb(new MongoError('Pool was force destroyed')); + } + } + + // Destroy the topology + return destroy(self, connections); + } + + // Clear out the reconnect if set + if (this.reconnectId) { + clearTimeout(this.reconnectId); + } + + // If we have a reconnect connection running, close + // immediately + if (this.reconnectConnection) { + this.reconnectConnection.destroy(); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + flushMonitoringOperations(self.queue); + + if (self.queue.length === 0) { + // Get all the known connections + var connections = self.availableConnections + .concat(self.inUseConnections) + .concat(self.nonAuthenticatedConnections) + .concat(self.connectingConnections); + + // Check if we have any in flight operations + for (var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if (connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections); + // } else if (self.queue.length > 0 && !this.reconnectId) { + } else { + // Ensure we empty the queue + _execute(self)(); + // Set timeout + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +}; + +// Prepare the buffer that Pool.prototype.write() uses to send to the server +var serializeCommands = function(self, commands, result, callback) { + // Base case when there are no more commands to serialize + if (commands.length === 0) return callback(null, result); + + // Pop off the zeroth command and serialize it + var thisCommand = commands.shift(); + var originalCommandBuffer = thisCommand.toBin(); + + // Check whether we and the server have agreed to use a compressor + if (self.options.agreedCompressor && !hasUncompressibleCommands(thisCommand)) { + // Transform originalCommandBuffer into OP_COMPRESSED + var concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); + var messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + var originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress(self, messageToBeCompressed, function(err, compressedMessage) { + if (err) return callback(err, null); + + // Create the msgHeader of OP_COMPRESSED + var msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE(MESSAGE_HEADER_SIZE + 9 + compressedMessage.length, 0); // messageLength + msgHeader.writeInt32LE(thisCommand.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + var compressionDetails = Buffer.alloc(9); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID + + // Push the concatenation of the OP_COMPRESSED message onto results + result.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + + // Continue recursing through the commands array + serializeCommands(self, commands, result, callback); + }); + } else { + // Push the serialization of the command onto results + result.push(originalCommandBuffer); + + // Continue recursing through the commands array + serializeCommands(self, commands, result, callback); + } +}; + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(commands, options, cb) { + var self = this; + // Ensure we have a callback + if (typeof options === 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // We need to have a callback function unless the message returns no response + if (!(typeof cb === 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // Pool was destroyed error out + if (this.state === DESTROYED || this.state === DESTROYING) { + // Callback with an error + if (cb) { + try { + cb(new MongoError('pool destroyed')); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + } + + return; + } + + if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + fullResult: false + }; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; + operation.promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw === 'boolean' ? options.raw : false; + operation.immediateRelease = + typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command === 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; + operation.session = options.session || null; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + // Custom socket Timeout + if (options.socketTimeout) { + operation.socketTimeout = options.socketTimeout; + } + + // Ensure commands is an array + if (!Array.isArray(commands)) { + commands = [commands]; + } + + // Get the requestId + operation.requestId = commands[commands.length - 1].requestId; + + if (hasSessionSupport(this.topology)) { + let sessionOptions = {}; + if (this.topology.clusterTime) { + sessionOptions = { $clusterTime: this.topology.clusterTime }; + } + + if (operation.session) { + // TODO: reenable when sessions development is complete + // if (operation.session.topology !== this.topology) { + // return cb( + // new MongoError('Sessions may only be used with the client they were created from') + // ); + // } + + if (operation.session.hasEnded) { + return cb(new MongoError('Use of expired sessions is not permitted')); + } + + if ( + operation.session.clusterTime && + operation.session.clusterTime.clusterTime.greaterThan( + sessionOptions.$clusterTime.clusterTime + ) + ) { + sessionOptions.$clusterTime = operation.session.clusterTime; + } + + sessionOptions.lsid = operation.session.id; + + // update the `lastUse` of the acquired ServerSession + operation.session.serverSession.lastUse = Date.now(); + } + + // decorate the commands with session-specific details + commands.forEach(command => { + if (command instanceof Query) { + if (command.query.$query) { + Object.assign(command.query.$query, sessionOptions); + } else { + Object.assign(command.query, sessionOptions); + } + } else { + Object.assign(command, sessionOptions); + } + }); + } + + // If command monitoring is enabled we need to modify the callback here + if (self.options.monitorCommands) { + // NOTE: there is only ever a single command, for some legacy reason I am unaware of we + // treat this as a potential array of commands + const command = commands[0]; + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operation.started = process.hrtime(); + operation.cb = (err, reply) => { + if (err) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operation.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operation.started) + ); + } else { + self.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operation.started) + ); + } + } + + if (typeof cb === 'function') cb(err, reply); + }; + } + + // Prepare the operation buffer + serializeCommands(self, commands, [], function(err, serializedCommands) { + if (err) throw err; + + // Set the operation's buffer to the serialization of the commands + operation.buffer = serializedCommands; + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if (options.monitoring) { + self.queue.unshift(operation); + } else { + self.queue.push(operation); + } + + // Attempt to execute the operation + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + }); +}; + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +var hasUncompressibleCommands = function(command) { + return uncompressibleCommands.some(function(cmd) { + return command.query.hasOwnProperty(cmd); + }); +}; + +// Remove connection method +function remove(connection, connections) { + for (var i = 0; i < connections.length; i++) { + if (connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if (remove(connection, self.availableConnections)) return; + if (remove(connection, self.inUseConnections)) return; + if (remove(connection, self.connectingConnections)) return; + if (remove(connection, self.nonAuthenticatedConnections)) return; +} + +// All event handlers +var handlers = ['close', 'message', 'error', 'timeout', 'parseError', 'connect']; + +function _createConnection(self) { + if (self.state === DESTROYED || self.state === DESTROYING) { + return; + } + var connection = new Connection(messageHandler(self), self.options); + + // Push the connection + self.connectingConnections.push(connection); + + // Handle any errors + var tempErrorHandler = function(_connection) { + return function() { + // Destroy the connection + _connection.destroy(); + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + // Start reconnection attempts + if (!self.reconnectId && self.options.reconnect) { + self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); + } + }; + }; + + // Handle successful connection + var tempConnectHandler = function(_connection) { + return function() { + // Destroyed state return + if (self.state === DESTROYED || self.state === DESTROYING) { + // Remove the connection from the list + removeConnection(self, _connection); + return _connection.destroy(); + } + + // Destroy all event emitters + handlers.forEach(function(e) { + _connection.removeAllListeners(e); + }); + + // Add the final handlers + _connection.once('close', connectionFailureHandler(self, 'close')); + _connection.once('error', connectionFailureHandler(self, 'error')); + _connection.once('timeout', connectionFailureHandler(self, 'timeout')); + _connection.once('parseError', connectionFailureHandler(self, 'parseError')); + + // Signal + reauthenticate(self, _connection, function(err) { + if (self.state === DESTROYED || self.state === DESTROYING) { + return _connection.destroy(); + } + // Remove the connection from the connectingConnections list + removeConnection(self, _connection); + + // Handle error + if (err) { + return _connection.destroy(); + } + + // If we are c at the moment + // Do not automatially put in available connections + // As we need to apply the credentials first + if (self.authenticating) { + self.nonAuthenticatedConnections.push(_connection); + } else { + // Push to available + self.availableConnections.push(_connection); + // Execute any work waiting + _execute(self)(); + } + }); + }; + }; + + // Add all handlers + connection.once('close', tempErrorHandler(connection)); + connection.once('error', tempErrorHandler(connection)); + connection.once('timeout', tempErrorHandler(connection)); + connection.once('parseError', tempErrorHandler(connection)); + connection.once('connect', tempConnectHandler(connection)); + + // Start connection + connection.connect(); +} + +function flushMonitoringOperations(queue) { + for (var i = 0; i < queue.length; i++) { + if (queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb( + new MongoError({ message: 'no connection available for monitoring', driver: true }) + ); + } + } +} + +function _execute(self) { + return function() { + if (self.state === DESTROYED) return; + // Already executing, skip + if (self.executing) return; + // Set pool as executing + self.executing = true; + + // Wait for auth to clear before continuing + function waitForAuth(cb) { + if (!self.authenticating) return cb(); + // Wait for a milisecond and try again + setTimeout(function() { + waitForAuth(cb); + }, 1); + } + + // Block on any auth in process + waitForAuth(function() { + // New pool connections are in progress, wait them to finish + // before executing any more operation to ensure distribution of + // operations + if (self.connectingConnections.length > 0) { + return; + } + + // As long as we have available connections + // eslint-disable-next-line + while (true) { + // Total availble connections + var totalConnections = + self.availableConnections.length + + self.connectingConnections.length + + self.inUseConnections.length; + + // No available connections available, flush any monitoring ops + if (self.availableConnections.length === 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + break; + } + + // No queue break + if (self.queue.length === 0) { + break; + } + + // Get a connection + var connection = null; + + // Locate all connections that have no work + var connections = []; + // Get a list of all connections + for (var i = 0; i < self.availableConnections.length; i++) { + if (self.availableConnections[i].workItems.length === 0) { + connections.push(self.availableConnections[i]); + } + } + + // No connection found that has no work on it, just pick one for pipelining + if (connections.length === 0) { + connection = + self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + } else { + connection = connections[self.connectionIndex++ % connections.length]; + } + + // Is the connection connected + if (connection.isConnected()) { + // Get the next work item + var workItem = self.queue.shift(); + + // If we are monitoring we need to use a connection that is not + // running another operation to avoid socket timeout changes + // affecting an existing operation + if (workItem.monitoring) { + var foundValidConnection = false; + + for (i = 0; i < self.availableConnections.length; i++) { + // If the connection is connected + // And there are no pending workItems on it + // Then we can safely use it for monitoring. + if ( + self.availableConnections[i].isConnected() && + self.availableConnections[i].workItems.length === 0 + ) { + foundValidConnection = true; + connection = self.availableConnections[i]; + break; + } + } + + // No safe connection found, attempt to grow the connections + // if possible and break from the loop + if (!foundValidConnection) { + // Put workItem back on the queue + self.queue.unshift(workItem); + + // Attempt to grow the pool if it's not yet maxsize + if (totalConnections < self.options.size && self.queue.length > 0) { + // Create a new connection + _createConnection(self); + } + + // Re-execute the operation + setTimeout(function() { + _execute(self)(); + }, 10); + + break; + } + } + + // Don't execute operation until we have a full pool + if (totalConnections < self.options.size) { + // Connection has work items, then put it back on the queue + // and create a new connection + if (connection.workItems.length > 0) { + // Lets put the workItem back on the list + self.queue.unshift(workItem); + // Create a new connection + _createConnection(self); + // Break from the loop + break; + } + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // Set current status of authentication process + workItem.authenticating = self.authenticating; + workItem.authenticatingTimestamp = self.authenticatingTimestamp; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (!workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Capture if write was successful + var writeSuccessful = true; + + // Put operation on the wire + if (Array.isArray(buffer)) { + for (i = 0; i < buffer.length; i++) { + writeSuccessful = connection.write(buffer[i]); + } + } else { + writeSuccessful = connection.write(buffer); + } + + // if the command is designated noResponse, call the callback immeditely + if (workItem.noResponse && typeof workItem.cb === 'function') { + workItem.cb(null, null); + } + + if (writeSuccessful && workItem.immediateRelease && self.authenticating) { + removeConnection(self, connection); + self.nonAuthenticatedConnections.push(connection); + } else if (writeSuccessful === false) { + // If write not successful put back on queue + self.queue.unshift(workItem); + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + } + } else { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + } + } + }); + + self.executing = false; + }; +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; diff --git a/node_modules/mongodb-core/lib/connection/utils.js b/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..e2d8dff --- /dev/null +++ b/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,113 @@ +'use strict'; + +var f = require('util').format, + require_optional = require('require_optional'); + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable: true, + set: function(value) { + if (typeof value !== 'boolean') throw new Error(f('%s required a boolean', prop.name)); + // Flip the bit to 1 + if (value === true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if (value === false && (values.flags & flag) === flag) values.flags ^= flag; + prop.value = value; + }, + get: function() { + return prop.value; + } + }); +}; + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable: true, + get: function() { + // Not parsed yet, parse it + if (values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if (typeof func === 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for (var name in fObj) tObj[name] = fObj[name]; + return tObj; +}; + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var retrieveBSON = function() { + var BSON = require('bson'); + BSON.native = false; + + try { + var optionalBSON = require_optional('bson-ext'); + if (optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } catch (err) {} // eslint-disable-line + + return BSON; +}; + +// Throw an error if an attempt to use Snappy is made when Snappy is not installed +var noSnappyWarning = function() { + throw new Error( + 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' + ); +}; + +// Facilitate loading Snappy optionally +var retrieveSnappy = function() { + var snappy = null; + try { + snappy = require_optional('snappy'); + } catch (error) {} // eslint-disable-line + if (!snappy) { + snappy = { + compress: noSnappyWarning, + uncompress: noSnappyWarning, + compressSync: noSnappyWarning, + uncompressSync: noSnappyWarning + }; + } + return snappy; +}; + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.debugOptions = debugOptions; +exports.retrieveBSON = retrieveBSON; +exports.retrieveSnappy = retrieveSnappy; diff --git a/node_modules/mongodb-core/lib/cursor.js b/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..d3ee7ea --- /dev/null +++ b/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,836 @@ +'use strict'; + +const Logger = require('./connection/logger'); +const retrieveBSON = require('./connection/utils').retrieveBSON; +const MongoError = require('./error').MongoError; +const MongoNetworkError = require('./error').MongoNetworkError; +const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; +const f = require('util').format; +const collationNotSupported = require('./utils').collationNotSupported; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null, + cmd: cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms + }; + + if (typeof options.session === 'object') { + this.cursorState.session = options.session; + } + + // Add promoteLong to cursor state + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.cursorState.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if (cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } +}; + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +}; + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +}; + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +}; + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +}; + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +}; + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +}; + +Cursor.prototype._endSession = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.cursorState.session; + + if (session && (options.force || session.owner === this)) { + this.cursorState.session = undefined; + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + return false; +}; + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +}; + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'issue initial query [%s] with flags [%s]', + JSON.stringify(self.cmd), + JSON.stringify(self.query) + ) + ); + } + + var queryCallback = function(err, r) { + if (err) return callback(err); + + // Get the raw message + var result = r.message; + + // Query failure bit set + if (result.queryFailure) { + return callback(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!self.cmd.find || (self.cmd.find && self.cmd.virtual === false)) && + (typeof result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have a an error document return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return callback(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + self.cursorState.lastCursorId = self.cursorState.cursorId; + self.cursorState.operationTime = result.documents[0].operationTime; + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); + } + + // Return after processing command cursor + return callback(null, result); + } + + if (Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, result); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + self.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.query === 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, result); + }; + + // Options passed to the pool + var queryOptions = {}; + + // If we have a raw query decorate the function + if (self.options.raw || self.cmd.raw) { + // queryCallback.raw = self.options.raw || self.cmd.raw; + queryOptions.raw = self.options.raw || self.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if (typeof self.query.documentsReturnedIn === 'string') { + // queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + queryOptions.documentsReturnedIn = self.query.documentsReturnedIn; + } + + // Add promote Long value if defined + if (typeof self.cursorState.promoteLongs === 'boolean') { + queryOptions.promoteLongs = self.cursorState.promoteLongs; + } + + // Add promote values if defined + if (typeof self.cursorState.promoteValues === 'boolean') { + queryOptions.promoteValues = self.cursorState.promoteValues; + } + + // Add promote values if defined + if (typeof self.cursorState.promoteBuffers === 'boolean') { + queryOptions.promoteBuffers = self.cursorState.promoteBuffers; + } + + if (typeof self.cursorState.session === 'object') { + queryOptions.session = self.cursorState.session; + } + + // Write the initial command out + self.server.s.pool.write(self.query, queryOptions, queryCallback); +}; + +Cursor.prototype._getmore = function(callback) { + if (this.logger.isDebug()) + this.logger.debug(f('schedule getMore call for query [%s]', JSON.stringify(this.query))); + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + + // Set the current batchSize + var batchSize = this.cursorState.batchSize; + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + batchSize > this.cursorState.limit + ) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + // Default pool + var pool = this.server.s.pool; + + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore( + this.bson, + this.ns, + this.cursorState, + batchSize, + raw, + pool, + this.options, + callback + ); +}; + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +}; + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead === true; +}; + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed === true; +}; + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified === true; +}; + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +}; + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice( + this.cursorState.cursorIndex, + this.cursorState.cursorIndex + length + ); + + // Transform the doc with passed in transformation method if provided + if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { + // Transform all the elements + for (var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + elements.length > this.cursorState.limit + ) { + elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +}; + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if ( + this.cursorState.cursorId == null || + this.cursorState.cursorId.isZero() || + this.cursorState.init === false + ) { + if (callback) callback(null, null); + return; + } + + // Default pool + var pool = this.server.s.pool; + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState, pool, callback); +}; + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if (this.cursorState.init) { + if (!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +}; + +/** + * Validate if the pool is dead and return error + */ +var isConnectionDead = function(self, callback) { + if (self.pool && self.pool.isDestroyed()) { + self.cursorState.killed = true; + const err = new MongoNetworkError( + f('connection to host %s:%s was destroyed', self.pool.host, self.pool.port) + ); + _setCursorNotifiedImpl(self, () => callback(err)); + return true; + } + + return false; +}; + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if (self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.killed = true; + setCursorNotified(self, callback); + return true; + } + + return false; +}; + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if (self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +}; + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if (self.cursorState.killed) { + setCursorNotified(self, callback); + return true; + } + + return false; +}; + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + setCursorNotified(self, callback); +}; + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); +}; + +var _setCursorNotifiedImpl = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + if (self._endSession) { + return self._endSession(undefined, () => callback()); + } + return callback(); +}; + +var nextFunction = function(self, callback) { + // We have notified about it + if (self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if (!self.cursorState.init) { + return initializeCursor(self, callback); + } + + // If we don't have a cursorId execute the first query + if (self.cursorState.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if (isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // query, cmd, options, cursorState, callback + self._find(function(err) { + if (err) return handleCallback(callback, err, null); + + if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { + self._endSession(); + } + + if ( + self.cursorState.documents.length === 0 && + self.cursorState.cursorId && + self.cursorState.cursorId.isZero() && + !self.cmd.tailable && + !self.cmd.awaitData + ) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.limit > 0 && + self.cursorState.currentLimit >= self.cursorState.limit + ) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if ( + self.cursorState.cursorIndex === self.cursorState.documents.length && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if (isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { + self._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + return nextFunction(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + setCursorDeadAndNotified(self, callback); + } else { + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +}; + +function initializeCursor(cursor, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!cursor.topology.isConnected(cursor.options)) { + // Only need this for single server, because repl sets and mongos + // will always continue trying to reconnect + if (cursor.topology._type === 'server' && !cursor.topology.s.options.reconnect) { + // Reconnect is disabled, so we'll never reconnect + return callback(new MongoError('no connection available')); + } + + if (cursor.disconnectHandler != null) { + if (cursor.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + + return cursor.disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + } + + return cursor.topology.selectServer(cursor.options, (err, server) => { + if (err) { + // Handle the error and add object to next method call + if (cursor.disconnectHandler != null) { + return cursor.disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + + return callback(err); + } + + cursor.server = server; + + // Set as init + cursor.cursorState.init = true; + + // error if collation not supported + if (collationNotSupported(cursor.server, cursor.cmd)) { + return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + } + + try { + cursor.query = cursor.server.wireProtocolHandler.command( + cursor.bson, + cursor.ns, + cursor.cmd, + cursor.cursorState, + cursor.topology, + cursor.options + ); + + if (cursor.query instanceof MongoError) { + return callback(cursor.query); + } + + // call `nextFunction` again now that we are initialized + nextFunction(cursor, callback); + } catch (err) { + return callback(err); + } + }); +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +}; + +module.exports = Cursor; diff --git a/node_modules/mongodb-core/lib/error.js b/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..c0d707c --- /dev/null +++ b/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,146 @@ +'use strict'; + +const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); + +/** + * Creates a new MongoError + * + * @augments Error + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + this.stack = message.stack; + } else { + if (typeof message === 'string') { + super(message); + } else { + super(message.message || message.errmsg || message.$err || 'n/a'); + for (var name in message) { + this[name] = message[name]; + } + } + + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'MongoError'; + this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; + } + + /** + * Creates a new MongoError object + * + * @param {Error|string|object} options The options used to create the error. + * @return {MongoError} A MongoError instance + * @deprecated Use `new MongoError()` instead. + */ + static create(options) { + return new MongoError(options); + } +} + +/** + * Creates a new MongoNetworkError + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoNetworkError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoNetworkError'; + + // This is added as part of the transactions specification + this.errorLabels = ['TransientTransactionError']; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoParseError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoParseError'; + } +} + +/** + * An error signifying a timeout event + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoTimeoutError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoTimeoutError'; + } +} + +/** + * An error thrown when the server reports a writeConcernError + * + * @param {Error|string|object} message The error message + * @param {object} result The result document (provided if ok: 1) + * @property {string} message The error message + * @property {object} [result] The result document (provided if ok: 1) + */ +class MongoWriteConcernError extends MongoError { + constructor(message, result) { + super(message); + this.name = 'MongoWriteConcernError'; + + if (result != null) { + this.result = result; + } + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436 // NotMasterOrSecondary +]); + +/** + * Determines whether an error is something the driver should attempt to retry + * + * @param {MongoError|Error} error + */ +function isRetryableError(error) { + return ( + RETRYABLE_ERROR_CODES.has(error.code) || + error instanceof MongoNetworkError || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +module.exports = { + MongoError, + MongoNetworkError, + MongoParseError, + MongoTimeoutError, + MongoWriteConcernError, + mongoErrorContextSymbol, + isRetryableError +}; diff --git a/node_modules/mongodb-core/lib/sdam/cursor.js b/node_modules/mongodb-core/lib/sdam/cursor.js new file mode 100644 index 0000000..f52d7b6 --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/cursor.js @@ -0,0 +1,749 @@ +'use strict'; + +const Logger = require('../connection/logger'); +const BSON = require('../connection/utils').retrieveBSON(); +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const mongoErrorContextSymbol = require('../error').mongoErrorContextSymbol; +const Long = BSON.Long; +const deprecate = require('util').deprecate; +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const ReadPreference = require('../topologies/read_preference'); + +/** + * Handle callback (including any exceptions thrown) + */ +function handleCallback(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * An internal class that embodies a cursor on MongoDB, allowing for iteration over the + * results returned from a query. + * + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +class Cursor { + /** + * Create a cursor + * + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + */ + constructor(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.s = { + cursorId: null, + cmd: cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms + }; + + if (typeof options.session === 'object') { + this.s.session = options.session; + } + + // Add promoteLong to cursor state + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.s.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.s.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.s.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.s.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.s.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.s.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.s.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.s.cursorId = Long.fromNumber(cmd); + this.s.lastCursorId = this.s.cursorId; + } else if (cmd instanceof Long) { + this.s.cursorId = cmd; + this.s.lastCursorId = cmd; + } + } + + setCursorBatchSize(value) { + this.s.batchSize = value; + } + + cursorBatchSize() { + return this.s.batchSize; + } + + setCursorLimit(value) { + this.s.limit = value; + } + + cursorLimit() { + return this.s.limit; + } + + setCursorSkip(value) { + this.s.skip = value; + } + + cursorSkip() { + return this.s.skip; + } + + _endSession(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.s.session; + if (session && (options.force || session.owner === this)) { + this.s.session = undefined; + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + + return false; + } + + /** + * Clone the cursor + * @method + * @return {Cursor} + */ + clone() { + return this.topology.cursor(this.ns, this.cmd, this.options); + } + + /** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ + isDead() { + return this.s.dead === true; + } + + /** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ + isKilled() { + return this.s.killed === true; + } + + /** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ + isNotified() { + return this.s.notified === true; + } + + /** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ + bufferedCount() { + return this.s.documents.length - this.s.cursorIndex; + } + + /** + * Kill the cursor + * + * @param {resultCallback} callback A callback function + */ + kill(callback) { + // Set cursor to dead + this.s.dead = true; + this.s.killed = true; + // Remove documents + this.s.documents = []; + + // If no cursor id just return + if (this.s.cursorId == null || this.s.cursorId.isZero() || this.s.init === false) { + if (callback) callback(null, null); + return; + } + + // Default pool + const pool = this.s.server.s.pool; + + // Execute command + this.s.server.s.wireProtocolHandler.killCursor(this.bson, this.ns, this.s, pool, callback); + } + + /** + * Resets the cursor + */ + rewind() { + if (this.s.init) { + if (!this.s.dead) { + this.kill(); + } + + this.s.currentLimit = 0; + this.s.init = false; + this.s.dead = false; + this.s.killed = false; + this.s.notified = false; + this.s.documents = []; + this.s.cursorId = null; + this.s.cursorIndex = 0; + } + } + + /** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ + readBufferedDocuments(number) { + const unreadDocumentsLength = this.s.documents.length - this.s.cursorIndex; + const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + let elements = this.s.documents.slice(this.s.cursorIndex, this.s.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if (this.s.transforms && typeof this.s.transforms.doc === 'function') { + // Transform all the elements + for (let i = 0; i < elements.length; i++) { + elements[i] = this.s.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if (this.s.limit > 0 && this.s.currentLimit + elements.length > this.s.limit) { + elements = elements.slice(0, this.s.limit - this.s.currentLimit); + this.kill(); + } + + // Adjust current limit + this.s.currentLimit = this.s.currentLimit + elements.length; + this.s.cursorIndex = this.s.cursorIndex + elements.length; + + // Return elements + return elements; + } + + /** + * Retrieve the next document from the cursor + * + * @param {resultCallback} callback A callback function + */ + next(callback) { + nextFunction(this, callback); + } +} + +Cursor.prototype._find = deprecate( + callback => _find(this, callback), + '_find() is deprecated, please stop using it' +); + +Cursor.prototype._getmore = deprecate( + callback => _getmore(this, callback), + '_getmore() is deprecated, please stop using it' +); + +function _getmore(cursor, callback) { + if (cursor.logger.isDebug()) { + cursor.logger.debug(`schedule getMore call for query [${JSON.stringify(cursor.query)}]`); + } + + // Determine if it's a raw query + const raw = cursor.options.raw || cursor.cmd.raw; + + // Set the current batchSize + let batchSize = cursor.s.batchSize; + if (cursor.s.limit > 0 && cursor.s.currentLimit + batchSize > cursor.s.limit) { + batchSize = cursor.s.limit - cursor.s.currentLimit; + } + + // Default pool + const pool = cursor.s.server.s.pool; + + // We have a wire protocol handler + cursor.s.server.s.wireProtocolHandler.getMore( + cursor.bson, + cursor.ns, + cursor.s, + batchSize, + raw, + pool, + cursor.options, + callback + ); +} + +function _find(cursor, callback) { + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + const queryCallback = (err, r) => { + if (err) return callback(err); + + // Get the raw message + const result = r.message; + + // Query failure bit set + if (result.queryFailure) { + return callback(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && + (result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have a an error document return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return callback(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + const id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + cursor.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursor.s.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.s.lastCursorId = cursor.s.cursorId; + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + cursor.s.documents = result.documents[0].cursor.firstBatch; + } + + // Return after processing command cursor + return callback(null, result); + } + + if (Array.isArray(result.documents[0].result)) { + cursor.s.documents = result.documents[0].result; + cursor.s.cursorId = Long.ZERO; + return callback(null, result); + } + } + + // Otherwise fall back to regular find path + cursor.s.cursorId = result.cursorId; + cursor.s.documents = result.documents; + cursor.s.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if (cursor.s.transforms && typeof cursor.s.transforms.query === 'function') { + cursor.s.documents = cursor.s.transforms.query(result); + } + + // Return callback + callback(null, result); + }; + + // Options passed to the pool + const queryOptions = {}; + + // If we have a raw query decorate the function + if (cursor.options.raw || cursor.cmd.raw) { + queryOptions.raw = cursor.options.raw || cursor.cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if (typeof cursor.query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = cursor.query.documentsReturnedIn; + } + + // Add promote Long value if defined + if (typeof cursor.s.promoteLongs === 'boolean') { + queryOptions.promoteLongs = cursor.s.promoteLongs; + } + + // Add promote values if defined + if (typeof cursor.s.promoteValues === 'boolean') { + queryOptions.promoteValues = cursor.s.promoteValues; + } + + // Add promote values if defined + if (typeof cursor.s.promoteBuffers === 'boolean') { + queryOptions.promoteBuffers = cursor.s.promoteBuffers; + } + + if (typeof cursor.s.session === 'object') { + queryOptions.session = cursor.s.session; + } + + // Write the initial command out + cursor.s.server.s.pool.write(cursor.query, queryOptions, queryCallback); +} + +/** + * Validate if the pool is dead and return error + */ +function isConnectionDead(cursor, callback) { + if (cursor.pool && cursor.pool.isDestroyed()) { + cursor.s.killed = true; + const err = new MongoNetworkError( + `connection to host ${cursor.pool.host}:${cursor.pool.port} was destroyed` + ); + _setCursorNotifiedImpl(cursor, () => callback(err)); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +function isCursorDeadButNotkilled(cursor, callback) { + // Cursor is dead but not marked killed, return null + if (cursor.s.dead && !cursor.s.killed) { + cursor.s.killed = true; + setCursorNotified(cursor, callback); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +function isCursorDeadAndKilled(cursor, callback) { + if (cursor.s.dead && cursor.s.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +function isCursorKilled(cursor, callback) { + if (cursor.s.killed) { + setCursorNotified(cursor, callback); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +function setCursorDeadAndNotified(cursor, callback) { + cursor.s.dead = true; + setCursorNotified(cursor, callback); +} + +/** + * Mark cursor as being notified + */ +function setCursorNotified(cursor, callback) { + _setCursorNotifiedImpl(cursor, () => handleCallback(callback, null, null)); +} + +function _setCursorNotifiedImpl(cursor, callback) { + cursor.s.notified = true; + cursor.s.documents = []; + cursor.s.cursorIndex = 0; + if (cursor._endSession) { + return cursor._endSession(undefined, () => callback()); + } + return callback(); +} + +function initializeCursorAndRetryNext(cursor, callback) { + cursor.topology.selectServer( + readPreferenceServerSelector(cursor.options.readPreference || ReadPreference.primary), + (err, server) => { + if (err) { + callback(err, null); + return; + } + + cursor.s.server = server; + cursor.s.init = true; + + // check if server supports collation + // NOTE: this should be a part of the selection predicate! + if (cursor.cmd && cursor.cmd.collation && cursor.server.description.maxWireVersion < 5) { + callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + return; + } + + try { + cursor.query = cursor.s.server.s.wireProtocolHandler.command( + cursor.bson, + cursor.ns, + cursor.cmd, + cursor.s, + cursor.topology, + cursor.options + ); + + nextFunction(cursor, callback); + } catch (err) { + callback(err); + return; + } + } + ); +} + +function nextFunction(cursor, callback) { + // We have notified about it + if (cursor.s.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(cursor, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(cursor, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(cursor, callback)) return; + + // We have just started the cursor + if (!cursor.s.init) { + return initializeCursorAndRetryNext(cursor, callback); + } + + // If we don't have a cursorId execute the first query + if (cursor.s.cursorId == null) { + // Check if pool is dead and return if not possible to + // execute the query against the db + if (isConnectionDead(cursor, callback)) return; + + // query, cmd, options, s, callback + return _find(cursor, function(err) { + if (err) return handleCallback(callback, err, null); + + if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { + cursor._endSession(); + } + + if ( + cursor.s.documents.length === 0 && + cursor.s.cursorId && + cursor.s.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + nextFunction(cursor, callback); + }); + } + + if (cursor.s.documents.length === cursor.s.cursorIndex && Long.ZERO.equals(cursor.s.cursorId)) { + setCursorDeadAndNotified(cursor, callback); + return; + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + setCursorDeadAndNotified(cursor, callback); + return; + } + + if ( + cursor.s.documents.length === cursor.s.cursorIndex && + cursor.cmd.tailable && + Long.ZERO.equals(cursor.s.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: cursor.cmd.tailable, + awaitData: cursor.cmd.awaitData + }) + ); + } + + if (cursor.s.cursorIndex === cursor.s.documents.length && !Long.ZERO.equals(cursor.s.cursorId)) { + // Ensure an empty cursor state + cursor.s.documents = []; + cursor.s.cursorIndex = 0; + + // Check if connection is dead and return if not possible to + if (isConnectionDead(cursor, callback)) return; + + // Execute the next get more + return _getmore(cursor, function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (cursor.s.cursorId && cursor.s.cursorId.isZero() && cursor._endSession) { + cursor._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + cursor.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + cursor.s.documents.length === 0 && + cursor.cmd.tailable && + Long.ZERO.equals(cursor.s.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: cursor.cmd.tailable, + awaitData: cursor.cmd.awaitData + }) + ); + } else if ( + cursor.s.documents.length === 0 && + cursor.cmd.tailable && + !Long.ZERO.equals(cursor.s.cursorId) + ) { + return nextFunction(cursor, callback); + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + return setCursorDeadAndNotified(cursor, callback); + } + + nextFunction(cursor, callback); + }); + } + + if (cursor.s.limit > 0 && cursor.s.currentLimit >= cursor.s.limit) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(cursor, callback); + } + + // Increment the current cursor limit + cursor.s.currentLimit += 1; + + // Get the document + let doc = cursor.s.documents[cursor.s.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + cursor.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(cursor, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + doc = cursor.s.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); +} + +module.exports = Cursor; diff --git a/node_modules/mongodb-core/lib/sdam/monitoring.js b/node_modules/mongodb-core/lib/sdam/monitoring.js new file mode 100644 index 0000000..dbd6b9f --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/monitoring.js @@ -0,0 +1,217 @@ +'use strict'; + +const ServerDescription = require('./server_description').ServerDescription; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** + * Published when server description changes, but does NOT include changes to the RTT. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {ServerDescription} previousDescription The previous server description + * @property {ServerDescription} newDescription The new server description + */ +class ServerDescriptionChangedEvent { + constructor(topologyId, address, previousDescription, newDescription) { + Object.assign(this, { topologyId, address, previousDescription, newDescription }); + } +} + +/** + * Published when server is initialized. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + */ +class ServerOpeningEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when server is closed. + * + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {Object} topologyId A unique identifier for the topology + */ +class ServerClosedEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when topology description changes. + * + * @property {Object} topologyId + * @property {TopologyDescription} previousDescription The old topology description + * @property {TopologyDescription} newDescription The new topology description + */ +class TopologyDescriptionChangedEvent { + constructor(topologyId, previousDescription, newDescription) { + Object.assign(this, { topologyId, previousDescription, newDescription }); + } +} + +/** + * Published when topology is initialized. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyOpeningEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Published when topology is closed. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyClosedEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Fired when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @property {Object} connectionId The connection id for the command + */ +class ServerHeartbeatStartedEvent { + constructor(connectionId) { + Object.assign(this, { connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster succeeds. + * + * @param {Number} duration The execution time of the event in ms + * @param {Object} reply The command reply + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatSucceededEvent { + constructor(duration, reply, connectionId) { + Object.assign(this, { duration, reply, connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * + * @param {Number} duration The execution time of the event in ms + * @param {MongoError|Object} failure The command failure + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatFailedEvent { + constructor(duration, failure, connectionId) { + Object.assign(this, { duration, failure, connectionId }); + } +} + +/** + * Performs a server check as described by the SDAM spec. + * + * NOTE: This method automatically reschedules itself, so that there is always an active + * monitoring process + * + * @param {Server} server The server to monitor + */ +function monitorServer(server) { + // executes a single check of a server + const checkServer = callback => { + let start = process.hrtime(); + + // emit a signal indicating we have started the heartbeat + server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); + + server.command( + 'admin.$cmd', + { ismaster: true }, + { + monitoring: true, + socketTimeout: server.s.options.connectionTimeout || 2000 + }, + function(err, result) { + let duration = calculateDurationInMs(start); + + if (err) { + server.emit( + 'serverHeartbeatFailed', + new ServerHeartbeatFailedEvent(duration, err, server.name) + ); + + return callback(err, null); + } + + const isMaster = result.result; + server.emit( + 'serverHeartbeatSucceded', + new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) + ); + + return callback(null, isMaster); + } + ); + }; + + const successHandler = isMaster => { + server.s.monitoring = false; + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); + + // schedule the next monitoring process + server.s.monitorId = setTimeout( + () => monitorServer(server), + server.s.options.heartbeatFrequencyMS + ); + }; + + // run the actual monitoring loop + server.s.monitoring = true; + checkServer((err, isMaster) => { + if (!err) { + successHandler(isMaster); + return; + } + + // According to the SDAM specification's "Network error during server check" section, if + // an ismaster call fails we reset the server's pool. If a server was once connected, + // change its type to `Unknown` only after retrying once. + + // TODO: we need to reset the pool here + + return checkServer((err, isMaster) => { + if (err) { + server.s.monitoring = false; + + // revert to `Unknown` by emitting a default description with no isMaster + server.emit('descriptionReceived', new ServerDescription(server.description.address)); + + // do not reschedule monitoring in this case + return; + } + + successHandler(isMaster); + }); + }); +} + +module.exports = { + ServerDescriptionChangedEvent, + ServerOpeningEvent, + ServerClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent, + monitorServer +}; diff --git a/node_modules/mongodb-core/lib/sdam/server.js b/node_modules/mongodb-core/lib/sdam/server.js new file mode 100644 index 0000000..caecc96 --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/server.js @@ -0,0 +1,413 @@ +'use strict'; +const EventEmitter = require('events'); +const MongoError = require('../error').MongoError; +const Pool = require('../connection/pool'); +const relayEvents = require('../utils').relayEvents; +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const Query = require('../connection/commands').Query; +const TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'); +const ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'); +const BSON = require('../connection/utils').retrieveBSON(); +const createClientInfo = require('../topologies/shared').createClientInfo; +const Logger = require('../connection/logger'); +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); +const monitorServer = require('./monitoring').monitorServer; + +/** + * + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + */ +class Server extends EventEmitter { + /** + * Create a server + * + * @param {ServerDescription} description + * @param {Object} options + */ + constructor(description, options) { + super(); + + this.s = { + // the server description + description, + // a saved copy of the incoming options + options, + // the server logger + logger: Logger('Server', options), + // the bson parser + bson: options.bson || new BSON(), + // client metadata for the initial handshake + clientInfo: createClientInfo(options), + // state variable to determine if there is an active server check in progress + monitoring: false, + // the connection pool + pool: null + }; + } + + get description() { + return this.s.description; + } + + get name() { + return this.s.description.address; + } + + /** + * Initiate server connect + * + * @param {Array} [options.auth] Array of auth options to apply on connect + */ + connect(options) { + options = options || {}; + + // do not allow connect to be called on anything that's not disconnected + if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { + throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); + } + + // create a pool + this.s.pool = new Pool(this, Object.assign(this.s.options, options, { bson: this.s.bson })); + + // Set up listeners + this.s.pool.on('connect', connectEventHandler(this)); + this.s.pool.on('close', closeEventHandler(this)); + + // this.s.pool.on('error', errorEventHandler(this)); + // this.s.pool.on('timeout', timeoutEventHandler(this)); + // this.s.pool.on('parseError', errorEventHandler(this)); + // this.s.pool.on('reconnect', reconnectEventHandler(this)); + // this.s.pool.on('reconnectFailed', errorEventHandler(this)); + + // relay all command monitoring events + relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // If auth settings have been provided, use them + if (options.auth) { + this.s.pool.connect.apply(this.s.pool, options.auth); + return; + } + + this.s.pool.connect(); + } + + /** + * Destroy the server connection + * + * @param {Boolean} [options.emitClose=false] Emit close event on destroy + * @param {Boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {Boolean} [options.force=false] Force destroy the pool + */ + destroy(callback) { + if (typeof callback === 'function') { + callback(null, null); + } + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + monitor() { + if (this.s.monitoring) return; + if (this.s.monitorId) clearTimeout(this.s.monitorId); + monitorServer(this); + } + + /** + * Execute a command + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const error = basicReadValidations(this, options); + if (error) { + return callback(error, null); + } + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (this.s.logger.isDebug()) { + this.s.logger.debug( + `executing command [${JSON.stringify({ ns, cmd, options })}] against ${this.name}` + ); + } + + // Check if we have collation support + if (this.description.maxWireVersion < 5 && cmd.collation) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + // Are we executing against a specific topology + const topology = options.topology || {}; + // Create the query object + const query = this.s.wireProtocolHandler.command(this.s.bson, ns, cmd, {}, topology, options); + // Set slave OK of the query + query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; + + // write options + const writeOptions = { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + command: true, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, + requestId: query.requestId, + socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null, + session: options.session || null + }; + + // write the operation to the pool + this.s.pool.write(query, writeOptions, callback); + } + + /** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); + } +} + +function basicWriteValidations(server) { + if (!server.s.pool) { + return new MongoError('server instance is not connected'); + } + + if (server.s.pool.isDestroyed()) { + return new MongoError('server instance pool was destroyed'); + } + + return null; +} + +function basicReadValidations(server, options) { + const error = basicWriteValidations(server, options); + if (error) { + return error; + } + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + return new MongoError('readPreference must be an instance of ReadPreference'); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const server = args.server; + const op = args.op; + const ns = args.ns; + const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; + + const error = basicWriteValidations(server, options); + if (error) { + callback(error, null); + return; + } + + // Check if we have collation support + if (server.description.maxWireVersion < 5 && options.collation) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + // Execute write + return server.s.wireProtocolHandler[op](server.s.pool, ns, server.s.bson, ops, options, callback); +} + +function saslSupportedMechs(options) { + if (!options) { + return {}; + } + + const authArray = options.auth || []; + const authMechanism = authArray[0] || options.authMechanism; + const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; + const user = authArray[2] || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function extractIsMasterError(err, result) { + if (err) return err; + if (result && result.result && result.result.ok === 0) { + return new MongoError(result.result); + } +} + +function executeServerHandshake(server, callback) { + // construct an `ismaster` query + const compressors = + server.s.options.compression && server.s.options.compression.compressors + ? server.s.options.compression.compressors + : []; + + const queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + const query = new Query( + server.s.bson, + 'admin.$cmd', + Object.assign( + { ismaster: true, client: server.s.clientInfo, compression: compressors }, + saslSupportedMechs(server.s.options) + ), + queryOptions + ); + + // execute the query + server.s.pool.write( + query, + { socketTimeout: server.s.options.connectionTimeout || 2000 }, + callback + ); +} + +function configureWireProtocolHandler(ismaster) { + // 3.2 wire protocol handler + if (ismaster.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(); + } + + // default to 2.6 wire protocol handler + return new TwoSixWireProtocolSupport(); +} + +function connectEventHandler(server) { + return function() { + // log information of received information if in info mode + // if (server.s.logger.isInfo()) { + // var object = err instanceof MongoError ? JSON.stringify(err) : {}; + // server.s.logger.info(`server ${server.name} fired event ${event} out with message ${object}`); + // } + + // begin initial server handshake + const start = process.hrtime(); + executeServerHandshake(server, (err, response) => { + // Set initial lastIsMasterMS - is this needed? + server.s.lastIsMasterMS = calculateDurationInMs(start); + + const serverError = extractIsMasterError(err, response); + if (serverError) { + server.emit('error', serverError); + return; + } + + // extract the ismaster from the server response + const isMaster = response.result; + + // compression negotation + if (isMaster && isMaster.compression) { + const localCompressionInfo = server.s.options.compression; + const localCompressors = localCompressionInfo.compressors; + for (var i = 0; i < localCompressors.length; i++) { + if (isMaster.compression.indexOf(localCompressors[i]) > -1) { + server.s.pool.options.agreedCompressor = localCompressors[i]; + break; + } + } + + if (localCompressionInfo.zlibCompressionLevel) { + server.s.pool.options.zlibCompressionLevel = localCompressionInfo.zlibCompressionLevel; + } + } + + // configure the wire protocol handler + server.s.wireProtocolHandler = configureWireProtocolHandler(isMaster); + + // log the connection event if requested + if (server.s.logger.isInfo()) { + server.s.logger.info( + `server ${server.name} connected with ismaster [${JSON.stringify(isMaster)}]` + ); + } + + // emit an event indicating that our description has changed + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, isMaster) + ); + + // emit a connect event + server.emit('connect', isMaster); + }); + }; +} + +function closeEventHandler(server) { + return function() { + server.emit('close'); + }; +} + +module.exports = Server; diff --git a/node_modules/mongodb-core/lib/sdam/server_description.js b/node_modules/mongodb-core/lib/sdam/server_description.js new file mode 100644 index 0000000..558b8cf --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/server_description.js @@ -0,0 +1,141 @@ +'use strict'; + +// An enumeration of server types we know about +const ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos +]); + +const ISMASTER_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'me', + 'hosts', + 'passives', + 'arbiters', + 'tags', + 'setName', + 'setVersion', + 'electionId', + 'primary', + 'logicalSessionTimeoutMinutes' +]; + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + */ +class ServerDescription { + /** + * Create a ServerDescription + * @param {String} address The address of the server + * @param {Object} [ismaster] An optional ismaster response for this server + * @param {Object} [options] Optional settings + * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) + */ + constructor(address, ismaster, options) { + options = options || {}; + ismaster = Object.assign( + { + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + ismaster + ); + + this.address = address; + this.error = null; + this.roundTripTime = options.roundTripTime || 0; + this.lastUpdateTime = Date.now(); + this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; + this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; + this.type = parseServerType(ismaster); + + // direct mappings + ISMASTER_FIELDS.forEach(field => { + if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; + }); + + // normalize case for hosts + this.hosts = this.hosts.map(host => host.toLowerCase()); + this.passives = this.passives.map(host => host.toLowerCase()); + this.arbiters = this.arbiters.map(host => host.toLowerCase()); + } + + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** + * @return {Boolean} Is this server available for reads + */ + get isReadable() { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** + * @return {Boolean} Is this server available for writes + */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } +} + +/** + * Parses an `ismaster` message and determines the server type + * + * @param {Object} ismaster The `ismaster` message to parse + * @return {ServerType} + */ +function parseServerType(ismaster) { + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +module.exports = { + ServerDescription, + ServerType +}; diff --git a/node_modules/mongodb-core/lib/sdam/server_selectors.js b/node_modules/mongodb-core/lib/sdam/server_selectors.js new file mode 100644 index 0000000..d082170 --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/server_selectors.js @@ -0,0 +1,206 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const TopologyType = require('./topology_description').TopologyType; +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +function writableServerSelector() { + return function(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); + }; +} + +// reducers +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoError( + `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary = servers.filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); + return servers.reduce((result, server) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + return servers; +} + +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +function tagSetReducer(readPreference, servers) { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, []); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce( + (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server) { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server) { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server) { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server) { + return server.type !== ServerType.Unknown; +} + +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new TypeError('Invalid read preference specified'); + } + + return function(topologyDescription, servers) { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) + ) { + throw new MongoError( + `Minimum wire version '${ + readPreference.minWireVersion + }' required, but found '${commonWireVersion}'` + ); + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + if (readPreference.mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (readPreference.mode === ReadPreference.SECONDARY) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } else if (readPreference.mode === ReadPreference.NEAREST) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(nearestFilter); + } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { + const result = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + + return result.length === 0 ? servers.filter(primaryFilter) : result; + } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } + }; +} + +module.exports = { + writableServerSelector, + readPreferenceServerSelector +}; diff --git a/node_modules/mongodb-core/lib/sdam/topology.js b/node_modules/mongodb-core/lib/sdam/topology.js new file mode 100644 index 0000000..bb43925 --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/topology.js @@ -0,0 +1,666 @@ +'use strict'; +const EventEmitter = require('events'); +const ServerDescription = require('./server_description').ServerDescription; +const TopologyDescription = require('./topology_description').TopologyDescription; +const TopologyType = require('./topology_description').TopologyType; +const monitoring = require('./monitoring'); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const MongoNetworkError = require('../error').MongoNetworkError; +const Server = require('./server'); +const relayEvents = require('../utils').relayEvents; +const ReadPreference = require('../topologies/read_preference'); +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const writableServerSelector = require('./server_selectors').writableServerSelector; +const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; +const Cursor = require('./cursor'); +const deprecate = require('util').deprecate; +const BSON = require('../connection/utils').retrieveBSON(); +const createCompressionInfo = require('../topologies/shared').createCompressionInfo; + +// Global state +let globalTopologyCounter = 0; + +// Constants +const TOPOLOGY_DEFAULTS = { + localThresholdMS: 15, + serverSelectionTimeoutMS: 10000, + heartbeatFrequencyMS: 30000, + minHeartbeatIntervalMS: 500 +}; + +/** + * A container of server instances representing a connection to a MongoDB topology. + * + * @fires Topology#serverOpening + * @fires Topology#serverClosed + * @fires Topology#serverDescriptionChanged + * @fires Topology#topologyOpening + * @fires Topology#topologyClosed + * @fires Topology#topologyDescriptionChanged + * @fires Topology#serverHeartbeatStarted + * @fires Topology#serverHeartbeatSucceeded + * @fires Topology#serverHeartbeatFailed + */ +class Topology extends EventEmitter { + /** + * Create a topology + * + * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to + * @param {Object} [options] Optional settings + * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled + */ + constructor(seedlist, options) { + super(); + if (typeof options === 'undefined') { + options = seedlist; + seedlist = []; + + // this is for legacy single server constructor support + if (options.host) { + seedlist.push({ host: options.host, port: options.port }); + } + } + + seedlist = seedlist || []; + options = Object.assign({}, TOPOLOGY_DEFAULTS, options); + + const topologyType = topologyTypeFromSeedlist(seedlist, options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = seedlist.reduce((result, seed) => { + const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; + result.set(address, new ServerDescription(address)); + return result; + }, new Map()); + + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options: Object.assign({}, options), + // initial seedlist of servers to connect to + seedlist: seedlist, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + null, + null, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, + // allow users to override the cursor factory + Cursor: options.cursorFactory || Cursor, + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]) + }; + + // amend options for server instance creation + this.s.options.compression = { compressors: createCompressionInfo(options) }; + } + + /** + * @return A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + + /** + * All raw connections + * @method + * @return {Connection[]} + */ + connections() { + return Array.from(this.s.servers.values()).reduce((result, server) => { + return result.concat(server.s.pool.allConnections()); + }, []); + } + + /** + * Initiate server connect + * + * @param {Object} [options] Optional settings + * @param {Array} [options.auth=null] Array of auth options to apply on connect + */ + connect(/* options */) { + // emit SDAM monitoring events + this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + connectServers(this, Array.from(this.s.description.servers.values())); + this.s.connected = true; + } + + /** + * Close this topology + */ + close(callback) { + // destroy all child servers + this.s.servers.forEach(server => server.destroy()); + + // emit an event for close + this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); + + this.s.connected = false; + + if (typeof callback === 'function') { + callback(null, null); + } + } + + /** + * Selects a server according to the selection predicate provided + * + * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window + * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + selectServers( + this, + selector, + options.serverSelectionTimeoutMS, + process.hrtime(), + (err, servers) => { + if (err) return callback(err, null); + callback(null, randomSelection(servers)); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param {object} serverDescription The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + + // emit monitoring events for this change + this.emit( + 'serverDescriptionChanged', + new monitoring.ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + this.s.description.servers.get(serverDescription.address) + ) + ); + + // update server list from updated descriptions + updateServers(this, serverDescription); + + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + /** + * Authenticate using a specified mechanism + * + * @param {String} mechanism The auth mechanism used for authentication + * @param {String} db The db we are authenticating against + * @param {Object} options Optional settings for the authenticating mechanism + * @param {authResultCallback} callback A callback function + */ + auth(mechanism, db, options, callback) { + callback(null, null); + } + + /** + * Logout from a database + * + * @param {String} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ + logout(db, callback) { + callback(null, null); + } + + // Basic operation support. Eventually this should be moved into command construction + // during the command refactor. + + /** + * Insert one or more documents + * + * @param {String} ns The full qualified namespace for this operation + * @param {Array} ops An array of documents to insert + * @param {Boolean} [options.ordered=true] Execute in order or out of order + * @param {Object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * + * @param {string} ns The fully qualified namespace for this operation + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); + } + + /** + * Execute a command + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + this.selectServer(readPreferenceServerSelector(readPreference), (err, server) => { + if (err) { + callback(err, null); + return; + } + + server.command(ns, cmd, options, callback); + }); + } + + /** + * Create a new cursor + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ + cursor(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + const CursorClass = options.cursorFactory || this.s.Cursor; + + return new CursorClass(this.s.bson, ns, cmd, options, topology, this.s.options); + } +} + +// legacy aliases +Topology.prototype.destroy = deprecate( + Topology.prototype.close, + 'destroy() is deprecated, please use close() instead' +); + +function topologyTypeFromSeedlist(seedlist, options) { + if (seedlist.length === 1 && !options.replicaSet) return TopologyType.Single; + if (options.replicaSet) return TopologyType.ReplicaSetNoPrimary; + return TopologyType.Unknown; +} + +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} + +/** + * Selects servers using the provided selector + * + * @private + * @param {Topology} topology The topology to select servers from + * @param {function} selector The actual predicate used for selecting servers + * @param {Number} timeout The max time we are willing wait for selection + * @param {Number} start A high precision timestamp for the start of the selection process + * @param {function} callback The callback used to convey errors or the resultant servers + */ +function selectServers(topology, selector, timeout, start, callback) { + const serverDescriptions = Array.from(topology.description.servers.values()); + let descriptions; + + try { + descriptions = selector + ? selector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + return callback(e, null); + } + + if (descriptions.length) { + const servers = descriptions.map(description => topology.s.servers.get(description.address)); + return callback(null, servers); + } + + const duration = calculateDurationInMs(start); + if (duration >= timeout) { + return callback(new MongoTimeoutError(`Server selection timed out after ${timeout} ms`)); + } + + const retrySelection = () => { + // ensure all server monitors attempt monitoring immediately + topology.s.servers.forEach(server => server.monitor()); + + const iterationTimer = setTimeout(() => { + callback(new MongoTimeoutError('Server selection timed out due to monitoring')); + }, topology.s.minHeartbeatIntervalMS); + + topology.once('topologyDescriptionChanged', () => { + // successful iteration, clear the check timer + clearTimeout(iterationTimer); + + // topology description has changed due to monitoring, reattempt server selection + selectServers(topology, selector, timeout, start, callback); + }); + }; + + // ensure we are connected + if (!topology.s.connected) { + topology.connect(); + + // we want to make sure we're still within the requested timeout window + const failToConnectTimer = setTimeout(() => { + callback(new MongoTimeoutError('Server selection timed out waiting to connect')); + }, timeout - duration); + + topology.once('connect', () => { + clearTimeout(failToConnectTimer); + retrySelection(); + }); + + return; + } + + retrySelection(); +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param {Topology} topology The topology responsible for the servers + * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + // publish an open event for each ServerDescription created + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options); + relayEvents(server, topology, [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed' + ]); + + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('connect', serverConnectEventHandler(server, topology)); + servers.set(serverDescription.address, server); + server.connect(); + return servers; + }, new Map()); +} + +function updateServers(topology, currentServerDescription) { + // update the internal server's description + if (topology.s.servers.has(currentServerDescription.address)) { + const server = topology.s.servers.get(currentServerDescription.address); + server.s.description = currentServerDescription; + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options); + relayEvents(server, topology, [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed' + ]); + + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('connect', serverConnectEventHandler(server, topology)); + topology.s.servers.set(serverDescription.address, server); + server.connect(); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + server.destroy(() => + topology.emit('serverClosed', new monitoring.ServerClosedEvent(topology.s.id, serverAddress)) + ); + } +} + +function serverConnectEventHandler(server, topology) { + return function(/* ismaster */) { + topology.emit('connect', topology); + }; +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const topology = args.topology; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + const willRetryWrite = + !args.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(topology) && + !options.session.inTransaction(); + + topology.selectServer(writableServerSelector(), (err, server) => { + if (err) { + callback(err, null); + return; + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!(err instanceof MongoNetworkError) && !err.message.match(/not master/)) { + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // execute the write operation + server[op](ns, ops, options, handler); + + // we need to increment the statement id if we're in a transaction + if (options.session && options.session.inTransaction()) { + options.session.incrementStatementId(ops.length); + } + }); +} + +/** + * A server opening SDAM monitoring event + * + * @event Topology#serverOpening + * @type {ServerOpeningEvent} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Topology#serverClosed + * @type {ServerClosedEvent} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Topology#serverDescriptionChanged + * @type {ServerDescriptionChangedEvent} + */ + +/** + * A topology open SDAM event + * + * @event Topology#topologyOpening + * @type {TopologyOpeningEvent} + */ + +/** + * A topology closed SDAM event + * + * @event Topology#topologyClosed + * @type {TopologyClosedEvent} + */ + +/** + * A topology structure SDAM change event + * + * @event Topology#topologyDescriptionChanged + * @type {TopologyDescriptionChangedEvent} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Topology#serverHeartbeatStarted + * @type {ServerHeartbeatStartedEvent} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Topology#serverHeartbeatFailed + * @type {ServerHearbeatFailedEvent} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Topology#serverHeartbeatSucceeded + * @type {ServerHeartbeatSucceededEvent} + */ + +module.exports = Topology; diff --git a/node_modules/mongodb-core/lib/sdam/topology_description.js b/node_modules/mongodb-core/lib/sdam/topology_description.js new file mode 100644 index 0000000..cd4f8fe --- /dev/null +++ b/node_modules/mongodb-core/lib/sdam/topology_description.js @@ -0,0 +1,364 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); + +// contstants related to compatability checks +const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +const MIN_SUPPORTED_WIRE_VERSION = 2; +const MAX_SUPPORTED_WIRE_VERSION = 5; + +// An enumeration of topology types we know about +const TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +// Representation of a deployment of servers +class TopologyDescription { + /** + * Create a TopologyDescription + * + * @param {string} topologyType + * @param {Map} serverDescriptions the a map of address to ServerDescription + * @param {string} setName + * @param {number} maxSetVersion + * @param {ObjectId} maxElectionId + */ + constructor(topologyType, serverDescriptions, setName, maxSetVersion, maxElectionId, options) { + options = options || {}; + + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType || TopologyType.Unknown; + this.setName = setName || null; + this.maxSetVersion = maxSetVersion || null; + this.maxElectionId = maxElectionId || null; + this.servers = serverDescriptions || new Map(); + this.stale = false; + this.compatible = true; + this.compatibilityError = null; + this.logicalSessionTimeoutMinutes = null; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; + this.localThresholdMS = options.localThresholdMS || 0; + this.options = options; + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ + serverDescription.minWireVersion + }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION}.`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ + serverDescription.maxWireVersion + }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); + this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { + if (server.logicalSessionTimeoutMinutes == null) return null; + if (result == null) return server.logicalSessionTimeoutMinutes; + return Math.min(result, server.logicalSessionTimeoutMinutes); + }, null); + } + + /** + * @returns The minimum reported wire version of all known servers + */ + get commonWireVersion() { + return Array.from(this.servers.values()) + .filter(server => server.type !== ServerType.Unknown) + .reduce( + (min, server) => + min == null ? server.maxWireVersion : Math.min(min, server.maxWireVersion), + null + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * + * @param {ServerDescription} serverDescription + */ + update(serverDescription) { + const address = serverDescription.address; + // NOTE: there are a number of prime targets for refactoring here + // once we support destructuring assignments + + // potentially mutated values + let topologyType = this.type; + let setName = this.setName; + let maxSetVersion = this.maxSetVersion; + let maxElectionId = this.maxElectionId; + + const serverType = serverDescription.type; + let serverDescriptions = new Map(this.servers); + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + this.options + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); + (topologyType = result[0]), (setName = result[1]); + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + setName, + serverDescription + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + this.options + ); + } + + /** + * Determines if the topology has a readable server available. See the table in the + * following section for behaviour rules. + * + * @param {ReadPreference} [readPreference] An optional read preference for determining if a readable server is present + * @return {Boolean} Whether there is a readable server in this topology + */ + hasReadableServer(/* readPreference */) { + // To be implemented when server selection is implemented + } + + /** + * Determines if the topology has a writable server available. See the table in the + * following section for behaviour rules. + * + * @return {Boolean} Whether there is a writable server in this topology + */ + hasWritableServer() { + return this.hasReadableServer(ReadPreference.primary); + } + + /** + * Determines if the topology has a definition for the provided address + * + * @param {String} address + * @return {Boolean} Whether the topology knows about this server + */ + hasServer(address) { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType) { + if (serverType === ServerType.Mongos) return TopologyType.Sharded; + if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; + return TopologyType.ReplicaSetNoPrimary; +} + +function updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId +) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; + const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; + if (serverDescription.setVersion != null && electionIdOID != null) { + if (maxSetVersion != null && maxElectionIdOID != null) { + if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const address of serverDescriptions.keys()) { + const server = serverDescriptions.get(address); + + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { + if (setName == null) { + throw new TypeError('setName is required'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { + let topologyType = TopologyType.ReplicaSetNoPrimary; + + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions) { + for (const addr of serverDescriptions.keys()) { + if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} + +module.exports = { + TopologyType, + TopologyDescription +}; diff --git a/node_modules/mongodb-core/lib/sessions.js b/node_modules/mongodb-core/lib/sessions.js new file mode 100644 index 0000000..429c06e --- /dev/null +++ b/node_modules/mongodb-core/lib/sessions.js @@ -0,0 +1,459 @@ +'use strict'; + +const retrieveBSON = require('./connection/utils').retrieveBSON; +const EventEmitter = require('events'); +const BSON = retrieveBSON(); +const Binary = BSON.Binary; +const uuidV4 = require('./utils').uuidV4; +const MongoError = require('./error').MongoError; +const isRetryableError = require('././error').isRetryableError; +const MongoNetworkError = require('./error').MongoNetworkError; +const MongoWriteConcernError = require('./error').MongoWriteConcernError; +const Transaction = require('./transactions').Transaction; +const TxnState = require('./transactions').TxnState; + +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new MongoError('Cannot use a session that has ended'); + if (typeof callback === 'function') { + callback(error, null); + return false; + } + + throw error; + } + + return true; +} + +/** + * Options to pass when creating a Client Session + * @typedef {Object} SessionOptions + * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session + * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. + */ + +/** + * A BSON document reflecting the lsid of a {@link ClientSession} + * @typedef {Object} SessionId + */ + +/** + * A class representing a client session on the server + * WARNING: not meant to be instantiated directly. + * @class + * @hideconstructor + */ +class ClientSession extends EventEmitter { + /** + * Create a client session. + * WARNING: not meant to be instantiated directly + * + * @param {Topology} topology The current client's topology (Internal Class) + * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) + * @param {SessionOptions} [options] Optional settings + * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + + if (topology == null) { + throw new Error('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + throw new Error('ClientSession requires a ServerSessionPool'); + } + + options = options || {}; + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.serverSession = sessionPool.acquire(); + this.clientOptions = clientOptions; + + this.supports = { + causalConsistency: + typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true + }; + + options = options || {}; + if (typeof options.initialClusterTime !== 'undefined') { + this.clusterTime = options.initialClusterTime; + } else { + this.clusterTime = null; + } + + this.operationTime = null; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** + * The server id associated with this session + * @type {SessionId} + */ + get id() { + return this.serverSession.id; + } + + /** + * Ends this session on the server + * + * @param {Object} [options] Optional settings. Currently reserved for future use + * @param {Function} [callback] Optional callback for completion of this operation + */ + endSession(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.hasEnded) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(); // pass in callback? + } + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + + // spec indicates that we should ignore all errors for `endSessions` + if (typeof callback === 'function') callback(null, null); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Used to determine if this session equals another + * @param {ClientSession} session + * @return {boolean} true if the sessions are equal + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + */ + incrementTransactionNumber() { + this.serverSession.txnNumber++; + } + + /** + * @returns {boolean} whether this session is currently in a transaction or not + */ + inTransaction() { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param {TransactionOptions} options Options for the transaction + */ + startTransaction(options) { + assertAlive(this); + if (this.inTransaction()) { + throw new MongoError('Transaction already in progress'); + } + + // increment txnNumber + this.incrementTransactionNumber(); + + // create transaction state + this.transaction = new Transaction( + Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) + ); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + commitTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'commitTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'commitTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + abortTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'abortTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'abortTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + * @ignore + */ + toBSON() { + throw new Error('ClientSession cannot be serialized to BSON.'); + } +} + +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + let txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + + // construct and send the command + const command = { [commandName]: 1 }; + + // apply a writeConcern if specified + if (session.transaction.options.writeConcern) { + Object.assign(command, { writeConcern: session.transaction.options.writeConcern }); + } else if (session.clientOptions && session.clientOptions.w) { + Object.assign(command, { writeConcern: { w: session.clientOptions.w } }); + } + + function commandHandler(e, r) { + if (commandName === 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + + if ( + e && + (e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e)) + ) { + if (e.errorLabels) { + const idx = e.errorLabels.indexOf('TransientTransactionError'); + if (idx !== -1) { + e.errorLabels.splice(idx, 1); + } + } else { + e.errorLabels = []; + } + + e.errorLabels.push('UnknownTransactionCommitResult'); + } + } else { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + } + + callback(e, r); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + function transactionError(err) { + return commandName === 'commitTransaction' ? err : null; + } + + // send the command + session.topology.command('admin.$cmd', command, { session }, (err, reply) => { + if (err && isRetryableError(err)) { + return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => + commandHandler(transactionError(_err), _reply) + ); + } + + commandHandler(transactionError(err), reply); + }); +} + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @ignore + */ +class ServerSession { + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = Date.now(); + this.txnNumber = 0; + } + + /** + * Determines if the server session has timed out. + * @ignore + * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" + * @return {boolean} true if the session has timed out. + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @ignore + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new Error('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** + * Ends all sessions in the session pool. + * @ignore + */ + endAllPooledSessions() { + if (this.sessions.length) { + this.topology.endSessions(this.sessions.map(session => session.id)); + this.sessions = []; + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession + * is created. + * @ignore + * @returns {ServerSession} + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * @ignore + * @param {ServerSession} session The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions[this.sessions.length - 1]; + if (session.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.unshift(session); + } + } +} + +module.exports = { + ClientSession, + ServerSession, + ServerSessionPool, + TxnState +}; diff --git a/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..22d0298 --- /dev/null +++ b/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,61 @@ +'use strict'; + +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results: [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: '' + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: 'fail', + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: '' + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/node_modules/mongodb-core/lib/topologies/mongos.js b/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..e6438bb --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1506 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const BasicCursor = require('../cursor'); +const Logger = require('../connection/logger'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const clone = require('./shared').clone; +const diff = require('./shared').diff; +const cloneOptions = require('./shared').cloneOptions; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15, + // Client info + clientInfo: createClientInfo(options), + // Authentication context + authenticationContexts: [] + }; + + // Set the client info + this.s.options.clientInfo = createClientInfo(options); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Are we authenticating + this.authenticating = false; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Description of the Replicaset + this.topologyDescription = { + topologyType: 'Unknown', + servers: [] + }; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; + + // Add event listener + EventEmitter.call(this); +}; + +inherits(Mongos, EventEmitter); +Object.assign(Mongos.prototype, SessionMixins); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable: true, + get: function() { + return 'mongos'; + } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + // Set connecting state + stateTransition(this, CONNECTING); + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, { + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + }); + + const serverDescriptionChangedCallback = event => { + self.emit('serverDescriptionChanged', event); + }; + + servers.forEach(function(server) { + server.on('serverDescriptionChanged', serverDescriptionChangedCallback); + server.on('destroy', () => + server.removeListener('serverDescriptionChanged', serverDescriptionChangedCallback) + ); + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +}; + +function handleEvent(self) { + return function() { + if (self.state === DESTROYED) return; + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Emit the left signal + self.emit('left', 'mongos', this); + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: this.name + }); + }; +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + + // Destroy the instance + if (self.state === DESTROYED) { + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if (event === 'connect') { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _this, function() { + // Get last known ismaster + self.ismaster = _this.lastIsMaster(); + + // Is this not a proxy, remove t + if (self.ismaster.msg === 'isdbgrid') { + // Add to the connectd list + for (var i = 0; i < self.connectedProxies.length; i++) { + if (self.connectedProxies[i].name === _this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + _this.destroy(); + return self.emit('failed', _this); + } + } + + // Remove the handlers + for (i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, _this); + // Emit the joined event + self.emit('joined', 'mongos', _this); + } else { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if (!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, _this.name)); + } + + // This is not a mongos proxy, remove it completely + removeProxyFrom(self.connectingProxies, _this); + // Emit the left event + self.emit('left', 'server', _this); + // Emit failed event + self.emit('failed', _this); + } + }); + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Trigger topologyMonitor + if (self.connectingProxies.length === 0) { + // Emit connected if we are connected + if (self.connectedProxies.length > 0 && self.state === CONNECTING) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.disconnectedProxies.length === 0) { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + self.s.logger.warn( + f('no mongos proxies found in seed list, did you mean to connect to a replicaset') + ); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, { firstConnect: true }); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.id, + address: server.name + }); + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +function pickProxy(self) { + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for (var i = 0; i < connectedProxies.length; i++) { + if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if ( + server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && + server.isConnected() + ) { + return true; + } + }); + + // We have no connectedProxies pick first of the connected ones + if (connectedProxies.length === 0) { + return self.connectedProxies[0]; + } + + // Get proxy + var proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } + + for (i = 0; i < to.length; i++) { + if (to[i].name === proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + // Return destroy + return this.destroy(); + } + + if (event === 'connect' && !self.authenticating) { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _self, function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.connectingProxies, self.connectedProxies, _self); + // Emit topology Change + emitTopologyDescriptionChanged(self); + // Emit joined event + self.emit('joined', 'mongos', _self); + }); + } else { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if (count === 0) { + callback(); + } + }; + }; + + // No new servers + if (count === 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10), + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + _server.destroy(); + removeProxyFrom(self.disconnectedProxies, _server); + + // Relay the server description change + server.on('serverDescriptionChanged', function(event) { + self.emit('serverDescriptionChanged', event); + }); + + // Emit opening server event + self.emit('serverOpening', { + topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, + address: server.name + }); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Connect to proxy + self.connectingProxies.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function applyAuthenticationContexts(self, server, callback) { + if (self.s.authenticationContexts.length === 0) { + return callback(); + } + + // Copy contexts to ensure no modificiation in the middle of + // auth process. + var authContexts = self.s.authenticationContexts.slice(0); + + // Apply one of the contexts + function applyAuth(authContexts, server, callback) { + if (authContexts.length === 0) return callback(); + // Get the first auth context + var authContext = authContexts.shift(); + // Copy the params + var customAuthContext = authContext.slice(0); + // Push our callback handler + customAuthContext.push(function(/* err */) { + applyAuth(authContexts, server, callback); + }); + + // Attempt authentication + server.auth.apply(server, customAuthContext); + } + + // Apply all auth contexts + applyAuth(authContexts, server, callback); +} + +function topologyMonitor(self, options) { + options = options || {}; + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: _server.name + }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: _server.name + }); + } + + cb(err, r); + } + ); + } + + // No proxies initiate monitor again + if (proxies.length === 0) { + // Emit close event if any listeners registered + if (self.listeners('close').length > 0 && self.state === CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // Are we connected ? emit connect event + if (self.state === CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.isConnected()) { + self.emit('reconnect', self); + } else if (!self.isConnected() && self.listeners('close').length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for (var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if (count === 0) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options) { + var self = this; + // Transition state + stateTransition(this, DESTROYED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + // Clear out authentication contexts + this.s.authenticationContexts = []; + + // Destroy all connecting servers + proxies.forEach(function(x) { + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: x.name + }); + + // Destroy the server + x.destroy(options); + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, x); + }); + // Emit the final topology change + emitTopologyDescriptionChanged(self); + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +// +// Operations +// + +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Pick a server + let server = pickProxy(self); + // No server found error out + if (!server) return callback(new MongoError('no mongos proxy available')); + + if (!options.retryWrites || !options.session || !isRetryableWritesSupported(self)) { + // Execute the command + return server[op](ns, ops, options, callback); + } + + // increment and assign txnNumber + options.willRetryWrite = true; + options.session.incrementTransactionNumber(); + + server[op](ns, ops, options, (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + // Pick another server + server = pickProxy(self); + + // No server found error out with original error + if (!server || !isRetryableWritesSupported(server)) { + return callback(err); + } + + // rerun the operation + server[op](ns, ops, options, callback); + }); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'insert', ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'update', ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation(this, 'remove', ns, ops, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Pick a proxy + var server = pickProxy(self); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if (server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Cloned options + var clonedOptions = cloneOptions(options); + clonedOptions.topology = self; + + const willRetryWrite = + !options.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, clonedOptions, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, clonedOptions, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Mongos.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + var currentContextIndex = 0; + + // If we don't have the mechanism fail + if (this.authProviders[mechanism] == null && mechanism !== 'default') { + return callback(new MongoError(f('auth provider %s does not exist', mechanism))); + } + + // Are we already authenticating, throw + if (this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!self.isConnected() && self.s.disconnectHandler != null) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.connectedProxies.slice(0); + // No servers return + if (servers.length === 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([ + function(err) { + count = count - 1; + // Save all the errors + if (err) errors.push({ name: server.name, err: err }); + // We are done + if (count === 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if (errors.length) { + // Remove the entry from the stored authentication contexts + self.s.authenticationContexts.splice(currentContextIndex, 0); + // Return error + return callback( + new MongoError({ + message: 'authentication fail', + errors: errors + }), + false + ); + } + + // Successfully authenticated session + callback(null, self); + } + } + ]); + + // Execute the auth only against non arbiter servers + if (!server.lastIsMaster().arbiterOnly) { + server.auth.apply(server, finalArguments); + } + } + + // Save current context index + currentContextIndex = this.s.authenticationContexts.length; + // Store the auth context and return the last index + this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); + + // Get total count + var count = servers.length; + // Authenticate against all servers + while (servers.length > 0) { + auth(servers.shift()); + } +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if (this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for (var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Now logout all the servers + var servers = this.connectedProxies.slice(0); + var count = servers.length; + if (count === 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if (err) errors.push({ name: _server.name, err: err }); + cb(); + }); + } + + // Execute logout on all server instances + for (i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if (count === 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if (errors.length) + return callback( + new MongoError({ + message: f('logout failed against db %s', dbName), + errors: errors + }), + false + ); + + // No errors + callback(); + } + }); + } +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {function} callback + */ +Mongos.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = pickProxy(this); + if (this.s.debug) this.emit('pickedServer', null, server); + callback(null, server); +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for (var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +}; + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + if (self.connectedProxies.length > 0) { + topology = 'Sharded'; + } + + // Generate description + var description = { + topologyType: topology, + servers: [] + }; + + // All proxies + var proxies = self.disconnectedProxies.concat(self.connectingProxies); + + // Add all the disconnected proxies + description.servers = description.servers.concat( + proxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Unknown'; + return description; + }) + ); + + // Add all the connected proxies + description.servers = description.servers.concat( + self.connectedProxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Mongos'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.topologyDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.topologyDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + if (diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + } + + // Set the new description + self.topologyDescription = description; + } +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/node_modules/mongodb-core/lib/topologies/read_preference.js b/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..dda610c --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,193 @@ +'use strict'; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @class + * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. + * @return {ReadPreference} + * @example + * const ReplSet = require('mongodb-core').ReplSet, + * ReadPreference = require('mongodb-core').ReadPreference, + * assert = require('assert'); + * + * const server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * const cursor = server.cursor( + * 'db.test', + * { find: 'db.test', query: {} }, + * { readPreference: new ReadPreference('secondary') } + * ); + * + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + * @see https://docs.mongodb.com/manual/core/read-preference/ + */ +const ReadPreference = function(mode, tags, options) { + // TODO(major): tags MUST be an array of tagsets + if (tags && !Array.isArray(tags)) { + console.warn( + 'ReadPreference tags must be an array, this will change in the next major version' + ); + + if (typeof tags.maxStalenessSeconds !== 'undefined') { + // this is likely an options object + options = tags; + tags = undefined; + } else { + tags = [tags]; + } + } + + this.mode = mode; + this.tags = tags; + + options = options || {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new TypeError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY || this.mode === true) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new TypeError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + } +}; + +// Support the deprecated `preference` property introduced in the porcelain layer +Object.defineProperty(ReadPreference.prototype, 'preference', { + enumerable: true, + get: function() { + return this.mode; + } +}); + +/* + * Read preference mode constants + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest'; + +const VALID_MODES = [ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + true, + false, + null +]; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.isValid = function(mode) { + return VALID_MODES.indexOf(mode) !== -1; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.prototype.isValid = function(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); +}; + +const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * @method + * @return {boolean} + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.mode) !== -1; +}; + +/** + * Are the two read preference equal + * @method + * @param {ReadPreference} readPreference The read preference with which to check equality + * @return {boolean} True if the two ReadPreferences are equivalent + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.mode === this.mode; +}; + +/** + * Return JSON representation + * @method + * @return {Object} A JSON representation of the ReadPreference + */ +ReadPreference.prototype.toJSON = function() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + return readPreference; +}; + +/** + * Primary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; diff --git a/node_modules/mongodb-core/lib/topologies/replset.js b/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..bac7450 --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1722 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const ReadPreference = require('./read_preference'); +const BasicCursor = require('../cursor'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const Logger = require('../connection/logger'); +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const ReplSetState = require('./replset_state'); +const clone = require('./shared').clone; +const Timeout = require('./shared').Timeout; +const Interval = require('./shared').Interval; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; + +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; + +var BSON = retrieveBSON(); + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); + // Validate list + if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); + // Validate entries + seedlist.forEach(function(e) { + if (typeof e.host !== 'string' || typeof e.port !== 'number') + throw new MongoError('seedlist entry must contain a host and port'); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, + setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // Client info + clientInfo: createClientInfo(options), + // Authentication context + authenticationContexts: [] + }; + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { + self.emit('topologyDescriptionChanged', r); + }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // All the authProviders + this.authProviders = options.authProviders || defaultAuthProviders(this.s.bson); + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, + fullsetup: false, + all: false + }; + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Are we authenticating + this.authenticating = false; + // Last ismaster + this.ismaster = null; + // Contains the intervalId + this.intervalIds = []; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; +}; + +inherits(ReplSet, EventEmitter); +Object.assign(ReplSet.prototype, SessionMixins); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable: true, + get: function() { + return 'replset'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; + } +}); + +function rexecuteOperations(self) { + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary: true }); + } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary: true }); + } +} + +function connectNewServers(self, servers, callback) { + // Count lefts + var count = servers.length; + var error = null; + + // Handle events + var _handleEvent = function(self, event) { + return function(err) { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + if (event === 'connect' && !self.authenticating) { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _self, function() { + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if (result) { + // Primary lastIsMaster store it + if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Enalbe the monitoring of the new server + monitorServer(_self.lastIsMaster().me, self, {}); + + // Rexecute any stalled operation + rexecuteOperations(self); + } else { + _self.destroy({ force: true }); + } + }); + } else if (event === 'connect' && self.authenticating) { + this.destroy({ force: true }); + } else if (event === 'error') { + error = err; + } + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Are we done finish up callback + if (count === 0) { + callback(error); + } + }; + }; + + // No new servers + if (count === 0) return callback(); + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10), + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +// Ping the server +var pingServer = function(self, server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); + + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + server.destroy({ force: true }); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + // Set the last updatedTime + var hrTime = process.hrtime(); + // Calculate the last update time + server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: server.name + }); + + // Remove server from the state + self.s.replicaSetState.remove(server); + } else { + // Update the server ismaster + server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { + server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if (server.lastIsMasterMS === -1) { + server.lastIsMasterMS = latencyMS; + } else if (server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; + } + + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: server.name + }); + } + + // Calculate the staleness for this server + self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); + + // Callback + cb(err, r); + } + ); +}; + +// Each server is monitored in parallel in their own timeout loop +var monitorServer = function(host, self, options) { + // If this is not the initial scan + // Is this server already being monitoried, then skip monitoring + if (!options.haInterval) { + for (var i = 0; i < self.intervalIds.length; i++) { + if (self.intervalIds[i].__host === host) { + return; + } + } + } + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + // Create the interval + var intervalId = new _process(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // clearInterval(intervalId); + intervalId.stop(); + return; + } + + // Do we already have server connection available for this host + var _server = self.s.replicaSetState.get(host); + + // Check if we have a known server connection and reuse + if (_server) { + // Ping the server + return pingServer(self, _server, function(err) { + if (err) { + // NOTE: should something happen here? + return; + } + + if (self.state === DESTROYED || self.state === UNREFERENCED) { + intervalId.stop(); + return; + } + + // Filter out all called intervaliIds + self.intervalIds = self.intervalIds.filter(function(intervalId) { + return intervalId.isRunning(); + }); + + // Initial sweep + if (_process === Timeout) { + if ( + self.state === CONNECTING && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + + // Start topology interval check + topologyMonitor(self, {}); + } + } else { + if ( + self.state === DISCONNECTED && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Emit connected sign + process.nextTick(function() { + self.emit('reconnect', self); + }); + } + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + }); + } + }, _haInterval); + + // Start the interval + intervalId.start(); + // Add the intervalId host name + intervalId.__host = host; + // Add the intervalId to our list of intervalIds + self.intervalIds.push(intervalId); +}; + +function topologyMonitor(self, options) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + options = options || {}; + + // Get the servers + var servers = Object.keys(self.s.replicaSetState.set); + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + if (_process === Timeout) { + return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { + // Don't emit errors if the connection was already + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no primary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no secondary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } + + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + }); + } else { + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + } + + // Run the reconnect process + function executeReconnect(self) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + var monitoringFrequencey = self.s.replicaSetState.hasPrimary() + ? _haInterval + : self.s.minHeartbeatFrequencyMS; + + // Create a timeout + self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); + }); + }; + } + + // Decide what kind of interval to use + var intervalTime = !self.s.replicaSetState.hasPrimary() + ? self.s.minHeartbeatFrequencyMS + : _haInterval; + + self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); +} + +function addServerToList(list, server) { + for (var i = 0; i < list.length; i++) { + if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; + } + + list.push(server); +} + +function handleEvent(self, event) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) + ); + } + + // Remove from the replicaset state + self.s.replicaSetState.remove(this); + + // Are we in a destroyed state return + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // If no primary and secondary available + if ( + !self.s.replicaSetState.hasPrimary() && + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + stateTransition(self, DISCONNECTED); + } else if (!self.s.replicaSetState.hasPrimary()) { + stateTransition(self, DISCONNECTED); + } + + addServerToList(self.s.connectingServers, this); + }; +} + +function applyAuthenticationContexts(self, server, callback) { + if (self.s.authenticationContexts.length === 0) { + return callback(); + } + + // Do not apply any auth contexts if it's an arbiter + if (server.lastIsMaster() && server.lastIsMaster().arbiterOnly) { + return callback(); + } + + // Copy contexts to ensure no modificiation in the middle of + // auth process. + var authContexts = self.s.authenticationContexts.slice(0); + + // Apply one of the contexts + function applyAuth(authContexts, server, callback) { + if (authContexts.length === 0) return callback(); + // Get the first auth context + var authContext = authContexts.shift(); + // Copy the params + var customAuthContext = authContext.slice(0); + // Push our callback handler + customAuthContext.push(function(/* err */) { + applyAuth(authContexts, server, callback); + }); + + // Attempt authentication + server.auth.apply(server, customAuthContext); + } + + // Apply all auth contexts + applyAuth(authContexts, server, callback); +} + +function shouldTriggerConnect(self) { + const isConnecting = self.state === CONNECTING; + const hasPrimary = self.s.replicaSetState.hasPrimary(); + const hasSecondary = self.s.replicaSetState.hasSecondary(); + const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; + const readPreferenceSecondary = + self.s.connectOptions.readPreference && + self.s.connectOptions.readPreference.equals(ReadPreference.secondary); + + return ( + (isConnecting && + ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || + (hasSecondary && secondaryOnlyConnectionAllowed) + ); +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s', + event, + this.name, + self.id + ) + ); + } + + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + // Check the type of server + if (event === 'connect') { + // Do we have authentication contexts that need to be applied + applyAuthenticationContexts(self, _this, function() { + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _this.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_this); + if (result === true) { + // Primary lastIsMaster store it + if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { + self.ismaster = _this.lastIsMaster(); + } + + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', + event, + _this.name, + self.id, + JSON.stringify(self.s.replicaSetState.set) + ) + ); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Do we have a primary or primaryAndSecondary + if (shouldTriggerConnect(self)) { + // We are connected + self.state = CONNECTED; + + // Set initial connect state + self.initialConnectState.connect = true; + // Emit connect event + process.nextTick(function() { + self.emit('connect', self); + }); + + topologyMonitor(self, {}); + } + } else if (result instanceof MongoError) { + _this.destroy({ force: true }); + self.destroy({ force: true }); + return self.emit('error', result); + } else { + _this.destroy({ force: true }); + } + }); + } else { + // Emit failure to connect + self.emit('failed', this); + + addServerToList(self.s.connectingServers, this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + + // Remove from the list from connectingServers + for (var i = 0; i < self.s.connectingServers.length; i++) { + if (self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { + topologyMonitor(self, { haInterval: 1 }); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + // Set connecting state + stateTransition(this, CONNECTING); + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, { + authProviders: self.authProviders, + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + }); + + // Error out as high availbility interval must be < than socketTimeout + if ( + this.s.options.socketTimeout > 0 && + this.s.options.socketTimeout <= this.s.options.haInterval + ) { + return self.emit( + 'error', + new MongoError( + f( + 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', + this.s.options.haInterval, + this.s.options.socketTimeout + ) + ) + ); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options) { + options = options || {}; + // Transition state + stateTransition(this, DESTROYED); + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + // Destroy the replicaset + this.s.replicaSetState.destroy(options); + // Clear out authentication contexts + this.s.authenticationContexts = []; + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options); + }); + + // Clear out all monitoring + for (var i = 0; i < this.intervalIds.length; i++) { + this.intervalIds[i].stop(); + } + + // Reset list of intervalIds + this.intervalIds = []; + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); +}; + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + // If secondaryOnlyConnectionAllowed and no primary but secondary + // return the secondaries ismaster result. + if ( + this.s.options.secondaryOnlyConnectionAllowed && + !this.s.replicaSetState.hasPrimary() && + this.s.replicaSetState.hasSecondary() + ) { + return this.s.replicaSetState.secondaries[0].lastIsMaster(); + } + + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() + : this.ismaster; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for (var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +}; + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we are authenticating signal not connected + // To avoid interleaving of operations + if (this.authenticating) return false; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +}; + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {function} callback + */ +ReplSet.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = this.s.replicaSetState.pickServer(options.readPreference); + if (this.s.debug) this.emit('pickedServer', options.readPreference, server); + callback(null, server); +}; + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +}; + +// +// Execute write operation +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + if (self.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + if (!self.s.replicaSetState.hasPrimary()) { + if (self.s.disconnectHandler) { + // Not connected but we have a disconnecthandler + return self.s.disconnectHandler.add(op, ns, ops, options, callback); + } else if (!willRetryWrite) { + // No server returned we had an error + return callback(new MongoError('no primary server found')); + } + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + // Per SDAM, remove primary from replicaset + if (self.s.replicaSetState.primary) { + self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + self.s.replicaSetState.primary[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if ( + readPreference.preference === 'primary' && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference === 'secondary' && + !this.s.replicaSetState.hasSecondary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference !== 'primary' && + !this.s.replicaSetState.hasSecondary() && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if (!(server instanceof Server)) return callback(server); + // Emit debug event + if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if (server == null) { + return callback( + new MongoError( + f('no server found that matches the provided readPreference %s', readPreference) + ) + ); + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + // Per SDAM, remove primary from replicaset + if (this.s.replicaSetState.primary) { + this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, options, cb); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + var currentContextIndex = 0; + + // If we don't have the mechanism fail + if (this.authProviders[mechanism] == null && mechanism !== 'default') { + return callback(new MongoError(f('auth provider %s does not exist', mechanism))); + } + + // Are we already authenticating, throw + if (this.authenticating) { + return callback(new MongoError('authentication or logout allready in process')); + } + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!this.isConnected() && self.s.disconnectHandler != null) { + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + return self.s.disconnectHandler.add('auth', db, allArgs, {}, callback); + } + } + + // Set to authenticating + this.authenticating = true; + // All errors + var errors = []; + + // Get all the servers + var servers = this.s.replicaSetState.allServers(); + // No servers return + if (servers.length === 0) { + this.authenticating = false; + callback(null, true); + } + + // Authenticate + function auth(server) { + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([ + function(err) { + count = count - 1; + // Save all the errors + if (err) errors.push({ name: server.name, err: err }); + // We are done + if (count === 0) { + // Auth is done + self.authenticating = false; + + // Return the auth error + if (errors.length) { + // Remove the entry from the stored authentication contexts + self.s.authenticationContexts.splice(currentContextIndex, 0); + // Return error + return callback( + new MongoError({ + message: 'authentication fail', + errors: errors + }), + false + ); + } + + // Successfully authenticated session + callback(null, self); + } + } + ]); + + if (!server.lastIsMaster().arbiterOnly) { + // Execute the auth only against non arbiter servers + server.auth.apply(server, finalArguments); + } else { + // If we are authenticating against an arbiter just ignore it + finalArguments.pop()(null); + } + } + + // Get total count + var count = servers.length; + + // Save current context index + currentContextIndex = this.s.authenticationContexts.length; + + // Store the auth context and return the last index + this.s.authenticationContexts.push([mechanism, db].concat(args.slice(0))); + + // Authenticate against all servers + while (servers.length > 0) { + auth(servers.shift()); + } +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.logout = function(dbName, callback) { + var self = this; + // Are we authenticating or logging out, throw + if (this.authenticating) { + throw new MongoError('authentication or logout allready in process'); + } + + // Ensure no new members are processed while logging out + this.authenticating = true; + + // Remove from all auth providers (avoid any reaplication of the auth details) + var providers = Object.keys(this.authProviders); + for (var i = 0; i < providers.length; i++) { + this.authProviders[providers[i]].logout(dbName); + } + + // Clear out any contexts associated with the db + self.s.authenticationContexts = self.s.authenticationContexts.filter(function(context) { + return context[1] !== dbName; + }); + + // Now logout all the servers + var servers = this.s.replicaSetState.allServers(); + var count = servers.length; + if (count === 0) return callback(); + var errors = []; + + function logoutServer(_server, cb) { + _server.logout(dbName, function(err) { + if (err) errors.push({ name: _server.name, err: err }); + cb(); + }); + } + + // Execute logout on all server instances + for (i = 0; i < servers.length; i++) { + logoutServer(servers[i], function() { + count = count - 1; + + if (count === 0) { + // Do not block new operations + self.authenticating = false; + // If we have one or more errors + if (errors.length) + return callback( + new MongoError({ + message: f('logout failed against db %s', dbName), + errors: errors + }), + false + ); + + // No errors + callback(); + } + }); + } +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/node_modules/mongodb-core/lib/topologies/replset_state.js b/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..4745173 --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,1099 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + diff = require('./shared').diff, + EventEmitter = require('events').EventEmitter, + Logger = require('../connection/logger'), + ReadPreference = require('./read_preference'), + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +var TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +var ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + topologyType: 'Unknown', + servers: [] + }; + + this.logicalSessionTimeoutMinutes = undefined; +}; + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +}; + +ReplSetState.prototype.hasPrimaryOrSecondary = function() { + return this.hasPrimary() || this.hasSecondary(); +}; + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +}; + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +}; + +ReplSetState.prototype.get = function(host) { + var servers = this.allServers(); + + for (var i = 0; i < servers.length; i++) { + if (servers[i].name.toLowerCase() === host.toLowerCase()) { + return servers[i]; + } + } + + return null; +}; + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +}; + +ReplSetState.prototype.destroy = function(options) { + // Destroy all sockets + if (this.primary) this.primary.destroy(options); + this.secondaries.forEach(function(x) { + x.destroy(options); + }); + this.arbiters.forEach(function(x) { + x.destroy(options); + }); + this.passives.forEach(function(x) { + x.destroy(options); + }); + this.ghosts.forEach(function(x) { + x.destroy(options); + }); + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; + this.primary = null; + // Emit the topology changed + emitTopologyDescriptionChanged(this); +}; + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for (var i = 0; i < servers.length; i++) { + if ( + !options.force && + servers[i].equals(server) && + servers[i].isConnected && + servers[i].isConnected() + ) { + return; + } + } + + // If we have it in the set remove it + if (this.set[serverName]) { + this.set[serverName].type = ServerType.Unknown; + this.set[serverName].electionId = null; + this.set[serverName].setName = null; + this.set[serverName].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if (this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Push to unknownServers + this.unknownServers.push(serverName); + + // Do we have a removeType + if (removeType) { + this.emit('left', removeType, server); + } +}; + +const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // + // Add any hosts + // + if (ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + hosts = hosts.map(function(s) { + return s.toLowerCase(); + }); + + // Add all hosts as unknownServers + for (var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if ( + this.unknownServers.indexOf(hosts[i]) === -1 && + (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) + ) { + this.unknownServers.push(hosts[i].toLowerCase()); + } + + if (!this.set[hosts[i]]) { + this.set[hosts[i]] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + }; + } + } + } + + // + // Unknown server + // + if (!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[serverName] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + // Update set information about the server instance + self.set[serverName].type = ServerType.Unknown; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if (self.unknownServers.indexOf(server.name) === -1) { + self.unknownServers.push(serverName); + } + + // Set the topology + return false; + } + + // Update logicalSessionTimeoutMinutes + if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { + if ( + self.logicalSessionTimeoutMinutes === undefined || + ismaster.logicalSessionTimeoutMinutes === null + ) { + self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } else { + self.logicalSessionTimeoutMinutes = Math.min( + self.logicalSessionTimeoutMinutes, + ismaster.logicalSessionTimeoutMinutes + ); + } + } + + // + // Is this a mongos + // + if (ismaster && ismaster.msg === 'isdbgrid') { + return false; + } + + // A RSOther instance + if ( + (ismaster.setName && ismaster.hidden) || + (ismaster.setName && + !ismaster.ismaster && + !ismaster.secondary && + !ismaster.arbiterOnly && + !ismaster.passive) + ) { + self.set[serverName] = { + type: ServerType.RSOther, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // A RSGhost instance + if (ismaster.isreplicaset) { + self.set[serverName] = { + type: ServerType.RSGhost, + setVersion: null, + electionId: null, + setName: null + }; + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // + // Standalone server, destroy and return + // + if (ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, { force: true }); + return false; + } + + // + // Server in maintanance mode + // + if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, { force: true }); + return false; + } + + // + // If the .me field does not match the passed in server + // + if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { + if (this.logger.isWarn()) { + this.logger.warn( + f( + 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', + server.name, + ismaster.me + ) + ); + } + + // Delete from the set + delete this.set[serverName]; + // Delete unknown servers + removeFrom(server, self.unknownServers); + + // Destroy the instance + server.destroy(); + + // Set the type of topology we have + if (this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if (!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null + }; + } + + return false; + } + + // + // Primary handling + // + if (!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if (this.setName && this.setName !== ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError( + f( + 'setName from ismaster does not match provided connection setName [%s] != [%s]', + ismaster.setName, + this.setName + ) + ); + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + if (result === 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if (result === 0 && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { + return x.toLowerCase(); + }); + var locationIndex = normalizedHosts.indexOf(serverName); + + // Validate that the server exists in the host list + if (locationIndex !== -1) { + self.primary = server; + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if (ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if (this.primary.equals(server) && currentSetName === ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if (currentSetName && currentSetName !== ismasterSetName) { + if (!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if (currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion > ismasterSetVersion) { + return false; + } + } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy(); + // Set the new instance + self.primary = server; + // Set the set information + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if (!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setVersion: null, + electionId: null, + setName: null + }; + } + + // + // Secondary handling + // + if ( + ismaster.secondary && + ismaster.setName && + !inList(ismaster, server, this.secondaries) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + // Emit secondary joined replicaset + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if ( + isArbiter(ismaster) && + !inList(ismaster, server, this.arbiters) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if ( + ismaster.passive && + ismaster.setName && + !inList(ismaster, server, this.passives) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy(); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy(); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + return false; +}; + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for (var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { + server.staleness = + server.lastUpdateTime - + server.lastWriteDate - + (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { + server.staleness = max - server.lastWriteDate + haInterval; + } +}; + +/** + * Recalculate all the staleness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for (var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +}; + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if (readPreference.maxStalenessSeconds != null) { + for (var i = 0; i < allservers.length; i++) { + if (allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError( + 'maxStalenessSeconds not supported by at least one of the replicaset members' + ); + } + } + } + + // Do we have the nearest readPreference + if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if ( + readPreference.preference === 'nearest' && + readPreference.maxStalenessSeconds != null + ) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { + return new MongoError('no secondary server available'); + } + + if ( + readPreference.equals(ReadPreference.secondaryPreferred) && + secondaries.length === 0 && + this.primary == null + ) { + return new MongoError('no secondary or primary server available'); + } + + if (readPreference.equals(ReadPreference.primary) && this.primary == null) { + return new MongoError('no primary server available'); + } + + // Secondary preferred or just secondaries + if ( + readPreference.equals(ReadPreference.secondaryPreferred) || + readPreference.equals(ReadPreference.secondary) + ) { + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } + + if (readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.primary; + } + + return null; + } + + // Primary preferred + if (readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if (this.primary) { + return this.primary; + } + + // Pick a secondary + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if (server) return server; + } + + // Return the primary + return this.primary; +}; + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if (readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for (var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for (var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for (var name in tags) { + if (serverTag[name] !== tags[name]) { + found = false; + } + } + + // Add to candidate list + if (found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +}; + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if (maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) + return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + var serverName = server.name.toLowerCase(); + // Update set information about the server instance + self.set[serverName].type = type; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = Buffer.from(id1.toHexString(), 'hex'); + var b = Buffer.from(id2.toHexString(), 'hex'); + + if (a === b) { + return 0; + } + + if (typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if (self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if (!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + }; + + // Add the primary to the list + if (self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat( + self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Add all the arbiters + description.servers = description.servers.concat( + self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + }) + ); + + // Add all the passives + description.servers = description.servers.concat( + self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.replicasetDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + // if(diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + // } + + // Set the new description + self.replicasetDescription = description; + } +} + +module.exports = ReplSetState; diff --git a/node_modules/mongodb-core/lib/topologies/server.js b/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..1fa0a3a --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1143 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + Logger = require('../connection/logger'), + debugOptions = require('../connection/utils').debugOptions, + retrieveBSON = require('../connection/utils').retrieveBSON, + Pool = require('../connection/pool'), + Query = require('../connection/commands').Query, + MongoError = require('../error').MongoError, + MongoNetworkError = require('../error').MongoNetworkError, + TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support'), + ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support'), + BasicCursor = require('../cursor'), + sdam = require('./shared'), + createClientInfo = require('./shared').createClientInfo, + createCompressionInfo = require('./shared').createCompressionInfo, + resolveClusterTime = require('./shared').resolveClusterTime, + SessionMixins = require('./shared').SessionMixins, + relayEvents = require('../utils').relayEvents; + +const collationNotSupported = require('../utils').collationNotSupported; + +function getSaslSupportedMechs(options) { + if (!options) { + return {}; + } + + const authArray = options.auth || []; + const authMechanism = authArray[0] || options.authMechanism; + const authSource = authArray[1] || options.authSource || options.dbName || 'admin'; + const user = authArray[2] || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 + ? 'scram-sha-256' + : 'scram-sha-1'; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return 'scram-sha-1'; + } + } + + // Default for wireprotocol < 3 + return 'mongocr'; +} + +function extractIsMasterError(err, result) { + if (err) { + return err; + } + + if (result && result.result && result.result.ok === 0) { + return new MongoError(result.result); + } +} + +// Used for filtering out fields for loggin +var debugFields = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'singleBufferSerializtion', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: options, + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || BasicCursor, + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: !!options.parent, + // Monitoring timeout + monitoringInterval: + typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, + // Topology id + topologyId: -1, + compression: { compressors: createCompressionInfo(options) }, + // Optional parent topology + parent: options.parent + }; + + // If this is a single deployment we need to track the clusterTime here + if (!this.s.parent) { + this.s.clusterTime = null; + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initialConnect = true; + // Wire protocol handler, default to oldest known protocol handler + // this gets changed when the first ismaster is called. + this.wireProtocolHandler = new TwoSixWireProtocolSupport(); + // Default type + this._type = 'server'; + // Set the client info + this.clientInfo = createClientInfo(options); + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +}; + +inherits(Server, EventEmitter); +Object.assign(Server.prototype, SessionMixins); + +Object.defineProperty(Server.prototype, 'type', { + enumerable: true, + get: function() { + return this._type; + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +// In single server deployments we track the clusterTime directly on the topology, however +// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the +// tracking objects so we can ensure we are gossiping the maximum time received from the +// server. +Object.defineProperty(Server.prototype, 'clusterTime', { + enumerable: true, + set: function(clusterTime) { + const settings = this.s.parent ? this.s.parent : this.s; + resolveClusterTime(settings, clusterTime); + }, + get: function() { + const settings = this.s.parent ? this.s.parent : this.s; + return settings.clusterTime || null; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +}; + +Server.disableServerAccounting = function() { + serverAccounting = false; +}; + +Server.servers = function() { + return servers; +}; + +Object.defineProperty(Server.prototype, 'name', { + enumerable: true, + get: function() { + return this.s.options.host + ':' + this.s.options.port; + } +}); + +function isSupportedServer(response) { + return response && typeof response.maxWireVersion === 'number' && response.maxWireVersion >= 2; +} + +function configureWireProtocolHandler(self, ismaster) { + // 3.2 wire protocol handler + if (ismaster.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(); + } + + // default to 2.6 wire protocol handler + return new TwoSixWireProtocolSupport(); +} + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ( + !self.s.pool.isConnected() && + self.s.options.reconnect && + self.s.disconnectHandler != null && + !options.monitoring + ) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if (!self.s.pool.isConnected()) { + callback(new MongoError(f('no connection available to server %s', self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if (self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var query = new Query(self.s.bson, 'admin.$cmd', { ismaster: true }, queryOptions); + // Get start time + var start = new Date().getTime(); + + // Execute the ismaster query + self.s.pool.write( + query, + { + socketTimeout: + typeof self.s.options.connectionTimeout !== 'number' + ? 2000 + : self.s.options.connectionTimeout, + monitoring: true + }, + function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if (self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if (result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + ); + }; +} + +var eventHandler = function(self, event) { + return function(err) { + // Log information of received information if in info mode + if (self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {}; + self.s.logger.info( + f('server %s fired event %s out with message %s', self.name, event, object) + ); + } + + // Handle connect event + if (event === 'connect') { + // Issue an ismaster command at connect + // Query options + var queryOptions = { numberToSkip: 0, numberToReturn: -1, checkKeys: false, slaveOk: true }; + // Create a query instance + var compressors = + self.s.compression && self.s.compression.compressors ? self.s.compression.compressors : []; + var query = new Query( + self.s.bson, + 'admin.$cmd', + Object.assign( + { ismaster: true, client: self.clientInfo, compression: compressors }, + getSaslSupportedMechs(self.s.options) + ), + queryOptions + ); + // Get start time + var start = new Date().getTime(); + // Execute the ismaster query + self.s.pool.write( + query, + { + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, result) { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + + const serverError = extractIsMasterError(err, result); + + if (serverError) { + self.destroy(); + return self.emit('error', serverError); + } + + if (!isSupportedServer(result.result)) { + self.destroy(); + const latestSupportedVersion = '2.6'; + const message = + 'Server at ' + + self.s.options.host + + ':' + + self.s.options.port + + ' reports wire version ' + + (result.result.maxWireVersion || 0) + + ', but this version of Node.js Driver requires at least 2 (MongoDB' + + latestSupportedVersion + + ').'; + return self.emit('error', new MongoError(message), self); + } + + // Determine whether the server is instructing us to use a compressor + if (result.result && result.result.compression) { + for (var i = 0; i < self.s.compression.compressors.length; i++) { + if (result.result.compression.indexOf(self.s.compression.compressors[i]) > -1) { + self.s.pool.options.agreedCompressor = self.s.compression.compressors[i]; + break; + } + } + + if (self.s.compression.zlibCompressionLevel) { + self.s.pool.options.zlibCompressionLevel = self.s.compression.zlibCompressionLevel; + } + } + + // Ensure no error emitted after initial connect when reconnecting + self.initialConnect = false; + // Save the ismaster + self.ismaster = result.result; + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if (self.ismaster.msg === 'isdbgrid') { + self._type = 'mongos'; + } + // Add the correct wire protocol handler + self.wireProtocolHandler = configureWireProtocolHandler(self, self.ismaster); + // Have we defined self monitoring + if (self.s.monitoring) { + self.monitoringProcessId = setTimeout( + monitoringProcess(self), + self.s.monitoringInterval + ); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + + if (!self.s.inTopology) { + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + } + ] + }); + } + + // Log the ismaster if available + if (self.s.logger.isInfo()) { + self.s.logger.info( + f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) + ); + } + + // Emit connect + self.emit('connect', self); + } + ); + } else if ( + event === 'error' || + event === 'parseError' || + event === 'close' || + event === 'timeout' || + event === 'reconnect' || + event === 'attemptReconnect' || + 'reconnectFailed' + ) { + // Remove server instance from accounting + if ( + serverAccounting && + ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 + ) { + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + if (event === 'close') { + // Closing emits a server description changed event going to unknown. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }); + } + + // Reconnect failed return error + if (event === 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if (self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if ( + self.s.pool.state === 'disconnected' && + self.initialConnect && + ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 + ) { + self.initialConnect = false; + return self.emit( + 'error', + new MongoNetworkError( + f('failed to connect to server [%s] on first connect [%s]', self.name, err) + ) + ); + } + + // Reconnect event, emit the server + if (event === 'reconnect') { + // Reconnecting emits a server description changed event going from unknown to the + // current server type. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + }; +}; + +/** + * Initiate server connect + * @method + * @param {array} [options.auth=null] Array of auth options to apply on connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if (serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); + } + + // Create a pool + self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Set up listeners for command monitoring + relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: self.id }); + } + + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Connect with optional auth settings + if (options.auth) { + self.s.pool.connect.apply(self.s.pool, options.auth); + } else { + self.s.pool.connect(); + } +}; + +/** + * Get the server description + * @method + * @return {object} + */ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name + }; + + // Add fields if available + if (ismaster.hosts) description.hosts = ismaster.hosts; + if (ismaster.arbiters) description.arbiters = ismaster.arbiters; + if (ismaster.passives) description.passives = ismaster.passives; + if (ismaster.setName) description.setName = ismaster.setName; + return description; +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if (!this.s.pool) return false; + return this.s.pool.isConnected(); +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if (!this.s.pool) return false; + return this.s.pool.isDestroyed(); +}; + +function basicWriteValidations(self) { + if (!self.s.pool) return new MongoError('server instance is not connected'); + if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error('readPreference must be an instance of ReadPreference'); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicReadValidations(self, options); + if (result) return callback(result); + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (self.s.logger.isDebug()) + self.s.logger.debug( + f( + 'executing command [%s] against %s', + JSON.stringify({ + ns: ns, + cmd: cmd, + options: debugOptions(debugFields, options) + }), + self.name + ) + ); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Are we executing against a specific topology + var topology = options.topology || {}; + // Create the query object + var query = self.wireProtocolHandler.command(self.s.bson, ns, cmd, {}, topology, options); + if (query instanceof MongoError) { + return callback(query, null); + } + + // Set slave OK of the query + query.slaveOk = options.readPreference ? options.readPreference.slaveOk() : false; + + // Write options + var writeOptions = { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + command: true, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, + requestId: query.requestId, + socketTimeout: typeof options.socketTimeout === 'number' ? options.socketTimeout : null, + session: options.session || null + }; + + // Write the operation to the pool + self.s.pool.write(query, writeOptions, callback); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return self.wireProtocolHandler.insert(self.s.pool, ns, self.s.bson, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.update(self.s.pool, ns, self.s.bson, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.wireProtocolHandler.remove(self.s.pool, ns, self.s.bson, ops, options, callback); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Server.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(this.s.bson, ns, cmd, options, topology, this.s.options); +}; + +/** + * Logout from a database + * @method + * @param {string} db The db we are logging out from + * @param {authResultCallback} callback A callback function + */ +Server.prototype.logout = function(dbName, callback) { + this.s.pool.logout(dbName, callback); +}; + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + + if (mechanism === 'default') { + mechanism = getDefaultAuthMechanism(self.ismaster); + } + + // Slice all the arguments off + var args = Array.prototype.slice.call(arguments, 0); + // Set the mechanism + args[0] = mechanism; + // Get the callback + var callback = args[args.length - 1]; + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'auth', db, args, {}, callback)) { + return; + } + + // Do not authenticate if we are an arbiter + if (this.lastIsMaster() && this.lastIsMaster().arbiterOnly) { + return callback(null, true); + } + + // Apply the arguments to the pool + self.s.pool.auth.apply(self.s.pool, args); +}; + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); + if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); + return false; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +}; + +/** + * Selects a server + * @return {Server} + */ +Server.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + + callback(null, this); +}; + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options) { + if (this._destroyed) return; + + options = options || {}; + var self = this; + + // Set the connections + if (serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if (this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // No pool, return + if (!self.s.pool) { + this._destroyed = true; + return; + } + + // Emit close event + if (options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if (options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if (self.listeners('serverClosed').length > 0) + self.emit('serverClosed', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Emit toplogy opening event if not in topology + if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: self.id }); + } + + if (self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force); + this._destroyed = true; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; diff --git a/node_modules/mongodb-core/lib/topologies/shared.js b/node_modules/mongodb-core/lib/topologies/shared.js new file mode 100644 index 0000000..4cb72ea --- /dev/null +++ b/node_modules/mongodb-core/lib/topologies/shared.js @@ -0,0 +1,434 @@ +'use strict'; + +const os = require('os'); +const f = require('util').format; +const ReadPreference = require('./read_preference'); +const Buffer = require('safe-buffer').Buffer; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +// Get package.json variable +var driverVersion = require('../../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +function createClientInfo(options) { + // Build default client information + var clientInfo = options.clientInfo + ? clone(options.clientInfo) + : { + driver: { + name: 'nodejs-core', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + } + }; + + // Is platform specified + if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { + clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); + } else if (!clientInfo.platform) { + clientInfo.platform = nodejsversion; + } + + // Do we have an application specific string + if (options.appname) { + // Cut at 128 bytes + var buffer = Buffer.from(options.appname); + // Return the truncated appname + var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; + // Add to the clientInfo + clientInfo.application = { name: appname }; + } + + return clientInfo; +} + +function createCompressionInfo(options) { + if (!options.compression || !options.compression.compressors) { + return []; + } + + // Check that all supplied compressors are valid + options.compression.compressors.forEach(function(compressor) { + if (compressor !== 'snappy' && compressor !== 'zlib') { + throw new Error('compressors must be at least one of snappy or zlib'); + } + }); + + return options.compression.compressors; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if (!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }; + } + + return self.s.serverDescription; +}; + +var emitServerDescriptionChanged = function(self, description) { + if (self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var getPreviousTopologyDescription = function(self) { + if (!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + } + ] + }; + } + + return self.s.topologyDescription; +}; + +var emitTopologyDescriptionChanged = function(self, description) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if (newType !== currentType) return true; + return false; +}; + +var getTopologyType = function(self, ismaster) { + if (!ismaster) { + ismaster = self.ismaster; + } + + if (!ismaster) return 'Unknown'; + if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; + if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if (ismaster.ismaster) return 'RSPrimary'; + if (ismaster.secondary) return 'RSSecondary'; + if (ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +}; + +var inquireServerState = function(self) { + return function(callback) { + if (self.s.state === 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { + if (!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: self.name + }); + + // Did the server change + if (changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: self.name + }); + } + + // Peforming an ismaster monitoring callback operation + if (typeof callback === 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +}; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for (var name in options) { + opts[name] = options[name]; + } + return opts; +}; + +function Interval(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setInterval(fn, time); + } + + return this; + }; + + this.stop = function() { + clearInterval(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function Timeout(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setTimeout(fn, time); + } + return this; + }; + + this.stop = function() { + clearTimeout(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + if (timer && timer._called) return false; + return timer !== false; + }; +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + }; + + // Previous entry + if (!previous) { + previous = { servers: [] }; + } + + // Check if we have any previous servers missing in the current ones + for (var i = 0; i < previous.servers.length; i++) { + var found = false; + + for (var j = 0; j < current.servers.length; j++) { + if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { + found = true; + break; + } + } + + if (!found) { + // Add to the diff + diff.servers.push({ + address: previous.servers[i].address, + from: previous.servers[i].type, + to: 'Unknown' + }); + } + } + + // Check if there are any severs that don't exist + for (j = 0; j < current.servers.length; j++) { + found = false; + + // Go over all the previous servers + for (i = 0; i < previous.servers.length; i++) { + if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { + found = true; + break; + } + } + + // Add the server to the diff + if (!found) { + diff.servers.push({ + address: current.servers[j].address, + from: 'Unknown', + to: current.servers[j].type + }); + } + } + + // Got through all the servers + for (i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for (j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { + // We had a change in state + if (prevServer.type !== currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +/** + * Shared function to determine clusterTime for a given topology + * + * @param {*} topology + * @param {*} clusterTime + */ +function resolveClusterTime(topology, $clusterTime) { + if (topology.clusterTime == null) { + topology.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { + topology.clusterTime = $clusterTime; + } + } +} + +// NOTE: this is a temporary move until the topologies can be more formally refactored +// to share code. +const SessionMixins = { + endSessions: function(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + // TODO: + // When connected to a sharded cluster the endSessions command + // can be sent to any mongos. When connected to a replica set the + // endSessions command MUST be sent to the primary if the primary + // is available, otherwise it MUST be sent to any available secondary. + // Is it enough to use: ReadPreference.primaryPreferred ? + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } +}; + +const RETRYABLE_WIRE_VERSION = 6; + +/** + * Determines whether the provided topology supports retryable writes + * + * @param {Mongos|Replset} topology + */ +const isRetryableWritesSupported = function(topology) { + const maxWireVersion = topology.lastIsMaster().maxWireVersion; + if (maxWireVersion < RETRYABLE_WIRE_VERSION) { + return false; + } + + if (!topology.logicalSessionTimeoutMinutes) { + return false; + } + + return true; +}; + +module.exports.SessionMixins = SessionMixins; +module.exports.resolveClusterTime = resolveClusterTime; +module.exports.inquireServerState = inquireServerState; +module.exports.getTopologyType = getTopologyType; +module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; +module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; +module.exports.cloneOptions = cloneOptions; +module.exports.createClientInfo = createClientInfo; +module.exports.createCompressionInfo = createCompressionInfo; +module.exports.clone = clone; +module.exports.diff = diff; +module.exports.Interval = Interval; +module.exports.Timeout = Timeout; +module.exports.isRetryableWritesSupported = isRetryableWritesSupported; diff --git a/node_modules/mongodb-core/lib/transactions.js b/node_modules/mongodb-core/lib/transactions.js new file mode 100644 index 0000000..6453aea --- /dev/null +++ b/node_modules/mongodb-core/lib/transactions.js @@ -0,0 +1,134 @@ +'use strict'; +const MongoError = require('./error').MongoError; + +let TxnState; +let stateMachine; + +(() => { + const NO_TRANSACTION = 'NO_TRANSACTION'; + const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; + const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; + const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; + const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; + const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; + + TxnState = { + NO_TRANSACTION, + STARTING_TRANSACTION, + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + }; + + stateMachine = { + [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], + [STARTING_TRANSACTION]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + ], + [TRANSACTION_IN_PROGRESS]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_ABORTED + ], + [TRANSACTION_COMMITTED]: [ + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + STARTING_TRANSACTION, + NO_TRANSACTION + ], + [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], + [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] + }; +})(); + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @typedef {Object} ReadConcern + * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level + * @see https://docs.mongodb.com/manual/reference/read-concern/ + */ + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @typedef {Object} WriteConcern + * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + +/** + * Configuration options for a transaction. + * @typedef {Object} TransactionOptions + * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction + * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction + * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction + */ + +/** + * A class maintaining state related to a server transaction. Internal Only + * @ignore + */ +class Transaction { + /** + * Create a transaction + * + * @ignore + * @param {TransactionOptions} [options] Optional settings + */ + constructor(options) { + options = options || {}; + + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + if (options.writeConcern || typeof options.w !== 'undefined') { + const w = options.writeConcern ? options.writeConcern.w : options.w; + if (w <= 0) { + throw new MongoError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; + } + + if (options.readConcern) this.options.readConcern = options.readConcern; + if (options.readPreference) this.options.readPreference = options.readPreference; + } + + /** + * @ignore + * @return Whether this session is presently in a transaction + */ + get isActive() { + return ( + [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 + ); + } + + /** + * Transition the transaction in the state machine + * @ignore + * @param {TxnState} state The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.indexOf(nextState) !== -1) { + this.state = nextState; + return; + } + + throw new MongoError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } +} + +module.exports = { TxnState, Transaction }; diff --git a/node_modules/mongodb-core/lib/uri_parser.js b/node_modules/mongodb-core/lib/uri_parser.js new file mode 100644 index 0000000..8ff66b1 --- /dev/null +++ b/node_modules/mongodb-core/lib/uri_parser.js @@ -0,0 +1,546 @@ +'use strict'; +const URL = require('url'); +const qs = require('querystring'); +const dns = require('dns'); +const MongoParseError = require('./error').MongoParseError; +const ReadPreference = require('./topologies/read_preference'); + +/** + * The following regular expression validates a connection string and breaks the + * provide string into the following capture groups: [protocol, username, password, hosts] + */ +const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup an `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param {string} uri The connection string to parse + * @param {object} options Optional user provided connection string options + * @param {function} callback + */ +function parseSrvConnectionString(uri, options, callback) { + const result = URL.parse(uri, true); + + if (result.hostname.split('.').length < 3) { + return callback(new MongoParseError('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + if (result.pathname && result.pathname.match(',')) { + return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoParseError('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback( + new MongoParseError('Server record does not share hostname with parent URI') + ); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map( + (address, i) => + i === 0 ? `${base}${address.name}:${address.port}` : `${address.name}:${address.port}` + ); + + let connectionString = `${connectionStrings.join(',')}/`; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && (!result.search || result.query['ssl'] == null)) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, (err, record) => { + if (err) { + if (err.code !== 'ENODATA') { + return callback(err); + } + record = null; + } + + if (record) { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + record = record[0]; + record = record.length > 1 ? record.join('') : record[0]; + if (record.indexOf('authSource') === -1 && record.indexOf('replicaSet') === -1) { + return callback( + new MongoParseError('Text record must only set `authSource` or `replicaSet`') + ); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseConnectionString(connectionString, options, callback); + }); + }); +} + +/** + * Parses a query string item according to the connection string spec + * + * @param {string} key The key for the parsed value + * @param {Array|String} value The value to parse + * @return {Array|Object|String} The parsed value + */ +function parseQueryStringItemValue(key, value) { + if (Array.isArray(value)) { + // deduplicate and simplify arrays + value = value.filter((v, idx) => value.indexOf(v) === idx); + if (value.length === 1) value = value[0]; + } else if (value.indexOf(':') > 0) { + value = value.split(',').reduce((result, pair) => { + const parts = pair.split(':'); + result[parts[0]] = parseQueryStringItemValue(key, parts[1]); + return result; + }, {}); + } else if (value.indexOf(',') > 0) { + value = value.split(',').map(v => { + return parseQueryStringItemValue(key, v); + }); + } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { + value = value.toLowerCase() === 'true'; + } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { + const numericValue = parseFloat(value); + if (!Number.isNaN(numericValue)) { + value = parseFloat(value); + } + } + + return value; +} + +// Options that are known boolean types +const BOOLEAN_OPTIONS = new Set([ + 'slaveok', + 'slave_ok', + 'sslvalidate', + 'fsync', + 'safe', + 'retrywrites', + 'j' +]); + +// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` +const STRING_OPTIONS = new Set(['authsource', 'replicaset']); + +// Supported text representations of auth mechanisms +// NOTE: this list exists in native already, if it is merged here we should deduplicate +const AUTH_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-X509', + 'MONGODB-CR', + 'DEFAULT', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'PLAIN' +]); + +// Lookup table used to translate normalized (lower-cased) forms of connection string +// options to their expected camelCase version +const CASE_TRANSLATION = { + replicaset: 'replicaSet', + connecttimeoutms: 'connectTimeoutMS', + sockettimeoutms: 'socketTimeoutMS', + maxpoolsize: 'maxPoolSize', + minpoolsize: 'minPoolSize', + maxidletimems: 'maxIdleTimeMS', + waitqueuemultiple: 'waitQueueMultiple', + waitqueuetimeoutms: 'waitQueueTimeoutMS', + wtimeoutms: 'wtimeoutMS', + readconcern: 'readConcern', + readconcernlevel: 'readConcernLevel', + readpreference: 'readPreference', + maxstalenessseconds: 'maxStalenessSeconds', + readpreferencetags: 'readPreferenceTags', + authsource: 'authSource', + authmechanism: 'authMechanism', + authmechanismproperties: 'authMechanismProperties', + gssapiservicename: 'gssapiServiceName', + localthresholdms: 'localThresholdMS', + serverselectiontimeoutms: 'serverSelectionTimeoutMS', + serverselectiontryonce: 'serverSelectionTryOnce', + heartbeatfrequencyms: 'heartbeatFrequencyMS', + appname: 'appName', + retrywrites: 'retryWrites', + uuidrepresentation: 'uuidRepresentation', + zlibcompressionlevel: 'zlibCompressionLevel' +}; + +/** + * Sets the value for `key`, allowing for any required translation + * + * @param {object} obj The object to set the key on + * @param {string} key The key to set the value for + * @param {*} value The value to set + * @param {object} options The options used for option parsing + */ +function applyConnectionStringOption(obj, key, value, options) { + // simple key translation + if (key === 'journal') { + key = 'j'; + } else if (key === 'wtimeoutms') { + key = 'wtimeout'; + } + + // more complicated translation + if (BOOLEAN_OPTIONS.has(key)) { + value = value === 'true' || value === true; + } else if (key === 'appname') { + value = decodeURIComponent(value); + } else if (key === 'readconcernlevel') { + key = 'readconcern'; + value = { level: value }; + } + + // simple validation + if (key === 'compressors') { + value = Array.isArray(value) ? value : [value]; + + if (!value.every(c => c === 'snappy' || c === 'zlib')) { + throw new MongoParseError( + 'Value for `compressors` must be at least one of: `snappy`, `zlib`' + ); + } + } + + if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { + throw new MongoParseError( + 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' + ); + } + + if (key === 'readpreference' && !ReadPreference.isValid(value)) { + throw new MongoParseError( + 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' + ); + } + + if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { + throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); + } + + // special cases + if (key === 'compressors' || key === 'zlibcompressionlevel') { + obj.compression = obj.compression || {}; + obj = obj.compression; + } + + if (key === 'authmechanismproperties') { + if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; + if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; + if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { + obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; + } + } + + // set the actual value + if (options.caseTranslate && CASE_TRANSLATION[key]) { + obj[CASE_TRANSLATION[key]] = value; + return; + } + + obj[key] = value; +} + +const USERNAME_REQUIRED_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-CR', + 'PLAIN', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +/** + * Modifies the parsed connection string object taking into account expectations we + * have for authentication-related options. + * + * @param {object} parsed The parsed connection string result + * @return The parsed connection string result possibly modified for auth expectations + */ +function applyAuthExpectations(parsed) { + if (parsed.options == null) { + return; + } + + const options = parsed.options; + const authSource = options.authsource || options.authSource; + if (authSource != null) { + parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + } + + const authMechanism = options.authmechanism || options.authMechanism; + if (authMechanism != null) { + if ( + USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && + (!parsed.auth || parsed.auth.username == null) + ) { + throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); + } + + if (authMechanism === 'GSSAPI') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-X509') { + if (parsed.auth && parsed.auth.password != null) { + throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); + } + + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'PLAIN') { + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + } + } + + // default to `admin` if nothing else was resolved + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); + } + + return parsed; +} + +/** + * Parses a query string according the connection string spec. + * + * @param {String} query The query string to parse + * @param {object} [options] The options used for options parsing + * @return {Object|Error} The parsed query string as an object, or an error if one was encountered + */ +function parseQueryString(query, options) { + const result = {}; + let parsedQueryString = qs.parse(query); + + for (const key in parsedQueryString) { + const value = parsedQueryString[key]; + if (value === '' || value == null) { + throw new MongoParseError('Incomplete key value pair for option'); + } + + const normalizedKey = key.toLowerCase(); + const parsedValue = parseQueryStringItemValue(normalizedKey, value); + applyConnectionStringOption(result, normalizedKey, parsedValue, options); + } + + // special cases for known deprecated options + if (result.wtimeout && result.wtimeoutms) { + delete result.wtimeout; + console.warn('Unsupported option `wtimeout` specified'); + } + + return Object.keys(result).length ? result : null; +} + +const PROTOCOL_MONGODB = 'mongodb'; +const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; +const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; + +/** + * Parses a MongoDB connection string + * + * @param {*} uri the MongoDB connection string to parse + * @param {object} [options] Optional settings. + * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization + * @param {parseCallback} callback + */ +function parseConnectionString(uri, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { caseTranslate: true }, options); + + // Check for bad uris before we parse + try { + URL.parse(uri); + } catch (e) { + return callback(new MongoParseError('URI malformed, cannot be parsed')); + } + + const cap = uri.match(HOSTS_RX); + if (!cap) { + return callback(new MongoParseError('Invalid connection string')); + } + + const protocol = cap[1]; + if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { + return callback(new MongoParseError('Invalid protocol provided')); + } + + if (protocol === PROTOCOL_MONGODB_SRV) { + return parseSrvConnectionString(uri, options, callback); + } + + const dbAndQuery = cap[4].split('?'); + const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; + const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; + + let parsedOptions; + try { + parsedOptions = parseQueryString(query, options); + } catch (parseError) { + return callback(parseError); + } + + parsedOptions = Object.assign({}, parsedOptions, options); + const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (cap[4].split('?')[0].indexOf('@') !== -1) { + return callback(new MongoParseError('Unescaped slash in userinfo section')); + } + + const authorityParts = cap[3].split('@'); + if (authorityParts.length > 2) { + return callback(new MongoParseError('Unescaped at-sign in authority section')); + } + + if (authorityParts.length > 1) { + const authParts = authorityParts.shift().split(':'); + if (authParts.length > 2) { + return callback(new MongoParseError('Unescaped colon in authority section')); + } + + auth.username = qs.unescape(authParts[0]); + auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; + } + + let hostParsingError = null; + const hosts = authorityParts + .shift() + .split(',') + .map(host => { + let parsedHost = URL.parse(`mongodb://${host}`); + if (parsedHost.path === '/:') { + hostParsingError = new MongoParseError('Double colon in host identifier'); + return null; + } + + // heuristically determine if we're working with a domain socket + if (host.match(/\.sock/)) { + parsedHost.hostname = qs.unescape(host); + parsedHost.port = null; + } + + if (Number.isNaN(parsedHost.port)) { + hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); + return; + } + + const result = { + host: parsedHost.hostname, + port: parsedHost.port ? parseInt(parsedHost.port) : 27017 + }; + + if (result.port === 0) { + hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); + return; + } + + if (result.port > 65535) { + hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); + return; + } + + if (result.port < 0) { + hostParsingError = new MongoParseError('Invalid port (negative number)'); + return; + } + + return result; + }) + .filter(host => !!host); + + if (hostParsingError) { + return callback(hostParsingError); + } + + if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { + return callback(new MongoParseError('No hostname or hostnames provided in connection string')); + } + + const result = { + hosts: hosts, + auth: auth.db || auth.username ? auth : null, + options: Object.keys(parsedOptions).length ? parsedOptions : null + }; + + if (result.auth && result.auth.db) { + result.defaultDatabase = result.auth.db; + } + + try { + applyAuthExpectations(result); + } catch (authError) { + return callback(authError); + } + + callback(null, result); +} + +module.exports = parseConnectionString; diff --git a/node_modules/mongodb-core/lib/utils.js b/node_modules/mongodb-core/lib/utils.js new file mode 100644 index 0000000..486e268 --- /dev/null +++ b/node_modules/mongodb-core/lib/utils.js @@ -0,0 +1,97 @@ +'use strict'; + +const crypto = require('crypto'); +const requireOptional = require('require_optional'); + +/** + * Generate a UUIDv4 + */ +const uuidV4 = () => { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +}; + +/** + * Returns the duration calculated from two high resolution timers in milliseconds + * + * @param {Object} started A high resolution timestamp created from `process.hrtime()` + * @returns {Number} The duration in milliseconds + */ +const calculateDurationInMs = started => { + const hrtime = process.hrtime(started); + return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; +}; + +/** + * Relays events for a given listener and emitter + * + * @param {EventEmitter} listener the EventEmitter to listen to the events from + * @param {EventEmitter} emitter the EventEmitter to relay the events to + */ +function relayEvents(listener, emitter, events) { + events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); +} + +function retrieveKerberos() { + let kerberos; + + try { + kerberos = requireOptional('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error('The `kerberos` module was not found. Please install it and try again.'); + } + + throw err; + } + + return kerberos; +} + +// Throw an error if an attempt to use EJSON is made when it is not installed +const noEJSONError = function() { + throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); +}; + +// Facilitate loading EJSON optionally +function retrieveEJSON() { + let EJSON = null; + try { + EJSON = requireOptional('mongodb-extjson'); + } catch (error) {} // eslint-disable-line + if (!EJSON) { + EJSON = { + parse: noEJSONError, + deserialize: noEJSONError, + serialize: noEJSONError, + stringify: noEJSONError, + setBSONModule: noEJSONError, + BSON: noEJSONError + }; + } + + return EJSON; +} + +/* + * Checks that collation is supported by server. + * + * @param {Server} [server] to check against + * @param {object} [cmd] object where collation may be specified + * @param {function} [callback] callback function + * @return true if server does not support collation + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && server.ismaster && server.ismaster.maxWireVersion < 5; +} + +module.exports = { + uuidV4, + calculateDurationInMs, + relayEvents, + collationNotSupported, + retrieveEJSON, + retrieveKerberos +}; diff --git a/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..bd509bb --- /dev/null +++ b/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,368 @@ +'use strict'; + +var copy = require('../connection/utils').copy, + retrieveBSON = require('../connection/utils').retrieveBSON, + KillCursor = require('../connection/commands').KillCursor, + GetMore = require('../connection/commands').GetMore, + Query = require('../connection/commands').Query, + f = require('util').format, + MongoError = require('../error').MongoError, + getReadPreference = require('./shared').getReadPreference; + +var BSON = retrieveBSON(), + Long = BSON.Long; + +var WireProtocol = function() {}; + +// +// Execute a write operation +var executeWrite = function(pool, bson, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError('insert must contain at least one document'); + if (typeof options === 'function') { + callback = options; + options = {}; + options = options || {}; + } + + // Split the ns up to get db and collection + var p = ns.split('.'); + var d = p.shift(); + // Options + var ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern; + + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = { command: true }; + if (typeof options.session !== 'undefined') opts.session = options.session; + var queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 }; + if (type === 'insert') queryOptions.checkKeys = true; + if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys; + // Ensure we support serialization of functions + if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; + // Do not serialize the undefined fields + if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; + + try { + // Create write command + var cmd = new Query(bson, f('%s.$cmd', d), writeCommand, queryOptions); + // Execute command + pool.write(cmd, opts, callback); + } catch (err) { + callback(err); + } +}; + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); +}; + +WireProtocol.prototype.update = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); +}; + +WireProtocol.prototype.remove = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); +}; + +WireProtocol.prototype.killCursor = function(bson, ns, cursorState, pool, callback) { + var cursorId = cursorState.cursorId; + // Create a kill cursor command + var killCursor = new KillCursor(bson, ns, [cursorId]); + + // Build killCursor options + const options = { + immediateRelease: true, + noResponse: true + }; + + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + // Execute the kill cursor command + if (pool && pool.isConnected()) { + try { + pool.write(killCursor, options, callback); + } catch (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + console.warn(err); + } + } + } +}; + +WireProtocol.prototype.getMore = function( + bson, + ns, + cursorState, + batchSize, + raw, + connection, + options, + callback +) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); + + // Query callback + var queryCallback = function(err, result) { + if (err) return callback(err); + // Get the raw message + var r = result.message; + + // If we have a timed out query or a cursor that was killed + if ((r.responseFlags & (1 << 0)) !== 0) { + return callback(new MongoError('cursor does not exist, was killed or timed out'), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId === 'number' ? Long.fromNumber(r.cursorId) : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null, null, r.connection); + }; + + // Contains any query options + var queryOptions = {}; + + // If we have a raw query decorate the function + if (raw) { + queryOptions.raw = raw; + } + + // Check if we need to promote longs + if (typeof cursorState.promoteLongs === 'boolean') { + queryOptions.promoteLongs = cursorState.promoteLongs; + } + + if (typeof cursorState.promoteValues === 'boolean') { + queryOptions.promoteValues = cursorState.promoteValues; + } + + if (typeof cursorState.promoteBuffers === 'boolean') { + queryOptions.promoteBuffers = cursorState.promoteBuffers; + } + + if (typeof cursorState.session === 'object') { + queryOptions.session = cursorState.session; + } + + // Write out the getMore command + connection.write(getMore, queryOptions, queryCallback); +}; + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if (cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options); + } else if (cursorState.cursorId != null) { + return; + } else if (cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f('command %s does not return a cursor', JSON.stringify(cmd))); + } +}; + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + // Ensure we have at least some options + options = options || {}; + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if (cursorState.limit === 0) { + numberToReturn = cursorState.batchSize; + } else if ( + cursorState.limit < 0 || + cursorState.limit < cursorState.batchSize || + (cursorState.limit > 0 && cursorState.batchSize === 0) + ) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + + // We have a Mongos topology, check if we need to add a readPreference + if (topology.type === 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + // Add special modifiers to the query + if (cmd.sort) findCmd['$orderby'] = cmd.sort; + if (cmd.hint) findCmd['$hint'] = cmd.hint; + if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; + if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; + if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; + if (cmd.min) findCmd['$min'] = cmd.min; + if (cmd.max) findCmd['$max'] = cmd.max; + if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; + if (cmd.comment) findCmd['$comment'] = cmd.comment; + if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; + + if (cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + findCmd['$explain'] = true; + } + + // Add the query + findCmd['$query'] = cmd.query; + + // Throw on majority readConcern passed in + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + f('server find command does not support a readConcern level of %s', cmd.readConcern.level) + ); + } + + // Remove readConcern, ensure no failing commands + if (cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, + numberToReturn: numberToReturn, + pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, + checkKeys: false, + returnFieldSelector: cmd.fields, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if (typeof cmd.tailable === 'boolean') { + query.tailable = cmd.tailable; + } + + if (typeof cmd.oplogReplay === 'boolean') { + query.oplogReplay = cmd.oplogReplay; + } + + if (typeof cmd.noCursorTimeout === 'boolean') { + query.noCursorTimeout = cmd.noCursorTimeout; + } + + if (typeof cmd.awaitData === 'boolean') { + query.awaitData = cmd.awaitData; + } + + if (typeof cmd.partial === 'boolean') { + query.partial = cmd.partial; + } + + // Return the query + return query; +}; + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + // Set empty options object + options = options || {}; + // Get the readPreference + var readPreference = getReadPreference(cmd, options); + + // Final query + var finalCmd = {}; + for (var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // Serialize functions + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + f( + 'server %s command does not support a readConcern level of %s', + JSON.stringify(cmd), + cmd.readConcern.level + ) + ); + } + + // Remove readConcern, ensure no failing commands + if (cmd.readConcern) delete cmd['readConcern']; + + // We have a Mongos topology, check if we need to add a readPreference + if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +}; + +module.exports = WireProtocol; diff --git a/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..d7c282f --- /dev/null +++ b/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,682 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const getReadPreference = require('./shared').getReadPreference; +const BSON = retrieveBSON(); +const Long = BSON.Long; +const ReadPreference = require('../topologies/read_preference'); +const TxnState = require('../transactions').TxnState; + +const WireProtocol = function() {}; + +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param {Object} command the command to decorate + * @param {ClientSession} session the session tracking transaction state + * @param {Object} [options] Optional settings passed to calling operation + * @param {Function} [callback] Optional callback passed from calling operation + * @return {MongoError|null} An error, if some error condition was met + */ +function decorateWithSessionsData(command, session, options) { + if (!session) { + return; + } + + // first apply non-transaction-specific sessions data + const serverSession = session.serverSession; + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options.willRetryWrite; + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); + } + + // now attempt to apply transaction-specific sessions data + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + // for causal consistency + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + + return; + } + + if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { + return new MongoError( + `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` + ); + } + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session.clientOptions.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +// +// Execute a write operation +function executeWrite(pool, bson, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError('insert must contain at least one document'); + if (typeof options === 'function') { + callback = options; + options = {}; + options = options || {}; + } + + // Split the ns up to get db and collection + const p = ns.split('.'); + const d = p.shift(); + // Options + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + // return skeleton + const writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + // Did we specify a write concern + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + // If we have collation passed in + if (options.collation) { + for (let i = 0; i < writeCommand[opsField].length; i++) { + if (!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + // Do we have bypassDocumentValidation set, then enable it on the write command + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // optionally decorate command with transactions data + const err = decorateWithSessionsData(writeCommand, options.session, options, callback); + if (err) { + return callback(err, null); + } + + // Options object + const opts = { command: true }; + if (typeof options.session !== 'undefined') opts.session = options.session; + const queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 }; + if (type === 'insert') queryOptions.checkKeys = true; + if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys; + + // Ensure we support serialization of functions + if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions; + // Do not serialize the undefined fields + if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined; + + try { + // Create write command + const cmd = new Query(bson, `${d}.$cmd`, writeCommand, queryOptions); + // Execute command + pool.write(cmd, opts, callback); + } catch (err) { + callback(err); + } +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'insert', 'documents', ns, ops, options, callback); +}; + +WireProtocol.prototype.update = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'update', 'updates', ns, ops, options, callback); +}; + +WireProtocol.prototype.remove = function(pool, ns, bson, ops, options, callback) { + executeWrite(pool, bson, 'delete', 'deletes', ns, ops, options, callback); +}; + +WireProtocol.prototype.killCursor = function(bson, ns, cursorState, pool, callback) { + // Build command namespace + const parts = ns.split(/\./); + // Command namespace + const commandns = `${parts.shift()}.$cmd`; + const cursorId = cursorState.cursorId; + // Create killCursor command + const killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + }; + + // Build Query object + const query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + returnFieldSelector: null + }); + + // Kill cursor callback + function killCursorCallback(err, result) { + if (err) { + if (typeof callback !== 'function') return; + return callback(err); + } + + // Result + const r = result.message; + // If we have a timed out query or a cursor that was killed + if ((r.responseFlags & (1 << 0)) !== 0) { + if (typeof callback !== 'function') return; + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(r.documents) || r.documents.length === 0) { + if (typeof callback !== 'function') return; + return callback( + new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) + ); + } + + // Return the result + if (typeof callback === 'function') { + callback(null, r.documents[0]); + } + } + + const options = { command: true }; + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + // Execute the kill cursor command + if (pool && pool.isConnected()) { + try { + pool.write(query, options, killCursorCallback); + } catch (err) { + killCursorCallback(err, null); + } + + return; + } + + // Callback + if (typeof callback === 'function') callback(null, null); +}; + +WireProtocol.prototype.getMore = function( + bson, + ns, + cursorState, + batchSize, + raw, + connection, + options, + callback +) { + options = options || {}; + // Build command namespace + const parts = ns.split(/\./); + // Command namespace + const commandns = `${parts.shift()}.$cmd`; + + // Create getMore command + const getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: Math.abs(batchSize) + }; + + // optionally decorate command with transactions data + const err = decorateWithSessionsData(getMoreCmd, options.session, options, callback); + if (err) { + return callback(err, null); + } + + if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + // Build Query object + const query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + returnFieldSelector: null + }); + + // Query callback + function queryCallback(err, result) { + if (err) return callback(err); + // Get the raw message + const r = result.message; + + // If we have a timed out query or a cursor that was killed + if ((r.responseFlags & (1 << 0)) !== 0) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + // Raw, return all the extracted documents + if (raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // We have an error detected + if (r.documents[0].ok === 0) { + return callback(new MongoError(r.documents[0])); + } + + // Ensure we have a Long valid cursor id + const cursorId = + typeof r.documents[0].cursor.id === 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0], r.connection); + } + + // Query options + const queryOptions = { command: true }; + + // If we have a raw query decorate the function + if (raw) { + queryOptions.raw = raw; + } + + // Add the result field needed + queryOptions.documentsReturnedIn = 'nextBatch'; + + // Check if we need to promote longs + if (typeof cursorState.promoteLongs === 'boolean') { + queryOptions.promoteLongs = cursorState.promoteLongs; + } + + if (typeof cursorState.promoteValues === 'boolean') { + queryOptions.promoteValues = cursorState.promoteValues; + } + + if (typeof cursorState.promoteBuffers === 'boolean') { + queryOptions.promoteBuffers = cursorState.promoteBuffers; + } + + if (typeof cursorState.session === 'object') { + queryOptions.session = cursorState.session; + } + + // Write out the getMore command + connection.write(query, queryOptions, queryCallback); +}; + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + options = options || {}; + // Check if this is a wire protocol command or not + const wireProtocolCommand = + typeof options.wireProtocolCommand === 'boolean' ? options.wireProtocolCommand : true; + + // Establish type of command + let query; + if (cmd.find && wireProtocolCommand) { + // Create the find command + query = executeFindCommand(bson, ns, cmd, cursorState, topology, options); + + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + } else if (cursorState.cursorId != null) { + return; + } else if (cmd) { + query = setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + return new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`); + } + + if (query instanceof MongoError) { + return query; + } + + // optionally decorate query with transaction data + const err = decorateWithSessionsData(query.query, options.session, options); + if (err) { + return err; + } + + return query; +}; + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +// FIND/GETMORE SPEC +// { +// “find”: , +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: , +// “limit”: , +// “batchSize”: , +// “singleBatch”: , +// “comment”: , +// “maxScan”: , +// “maxTimeMS”: , +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: , +// “showRecordId”: , +// “snapshot”: , +// “tailable”: , +// “oplogReplay”: , +// “noCursorTimeout”: , +// “awaitData”: , +// “partial”: , +// “$readPreference”: { ... } +// } + +// +// Execute a find command +function executeFindCommand(bson, ns, cmd, cursorState, topology, options) { + // Ensure we have at least some options + options = options || {}; + // Get the readPreference + const readPreference = getReadPreference(cmd, options); + + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + const parts = ns.split(/\./); + // Command namespace + const commandns = `${parts.shift()}.$cmd`; + + // Build actual find command + let findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if (cmd.query) { + // Check if the user is passing in the $query parameter + if (cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + // Sort value + let sortValue = cmd.sort; + + // Handle issue of sort being an Array + if (Array.isArray(sortValue)) { + const sortObject = {}; + + if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { + let sortDirection = sortValue[1]; + // Translate the sort order text + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for (var i = 0; i < sortValue.length; i++) { + let sortDirection = sortValue[i][1]; + // Translate the sort order text + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + // Add sort to command + if (cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if (cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if (cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if (cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if (cmd.limit) findCmd.limit = cmd.limit; + + // Check if we wish to have a singleBatch + if (cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // Add a batchSize + if (typeof cmd.batchSize === 'number') { + if (cmd.batchSize < 0) { + if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { + findCmd.limit = Math.abs(cmd.batchSize); + } + + findCmd.singleBatch = true; + } + + findCmd.batchSize = Math.abs(cmd.batchSize); + } + + // If we have comment set + if (cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if (cmd.min) findCmd.min = cmd.min; + + // If we have max + if (cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; + + // If we have showDiskLoc set + findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; + + // If we have snapshot set + if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if (cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if (cmd.partial) findCmd.partial = cmd.partial; + + // If we have collation passed in + if (cmd.collation) findCmd.collation = cmd.collation; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if (cmd.explain) { + findCmd = { + explain: findCmd + }; + } + + // Did we provide a readConcern + if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { + findCmd = { + $query: findCmd, + $readPreference: readPreference.toJSON() + }; + } + + // optionally decorate query with transaction data + const err = decorateWithSessionsData(findCmd, options.session, options); + if (err) { + return err; + } + + // Build Query object + const query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, + numberToReturn: 1, + checkKeys: false, + returnFieldSelector: null, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +function setupCommand(bson, ns, cmd, cursorState, topology, options) { + // Set empty options object + options = options || {}; + // Get the readPreference + const readPreference = getReadPreference(cmd, options); + + // Final query + let finalCmd = {}; + for (let name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + const parts = ns.split(/\./); + + // Serialize functions + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + // We have a Mongos topology, check if we need to add a readPreference + if (topology.type === 'mongos' && readPreference && readPreference.preference !== 'primary') { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + // optionally decorate query with transaction data + const err = decorateWithSessionsData(finalCmd, options.session, options); + if (err) { + return err; + } + + // Build Query object + const query = new Query(bson, `${parts.shift()}.$cmd`, finalCmd, { + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +module.exports = WireProtocol; diff --git a/node_modules/mongodb-core/lib/wireprotocol/compression.js b/node_modules/mongodb-core/lib/wireprotocol/compression.js new file mode 100644 index 0000000..4b908e6 --- /dev/null +++ b/node_modules/mongodb-core/lib/wireprotocol/compression.js @@ -0,0 +1,73 @@ +'use strict'; + +var Snappy = require('../connection/utils').retrieveSnappy(), + zlib = require('zlib'); + +var compressorIDs = { + snappy: 1, + zlib: 2 +}; + +var uncompressibleCommands = [ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]; + +// Facilitate compressing a message using an agreed compressor +var compress = function(self, dataToBeCompressed, callback) { + switch (self.options.agreedCompressor) { + case 'snappy': + Snappy.compress(dataToBeCompressed, callback); + break; + case 'zlib': + // Determine zlibCompressionLevel + var zlibOptions = {}; + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new Error( + 'Attempt to compress message using unknown compressor "' + + self.options.agreedCompressor + + '".' + ); + } +}; + +// Decompress a message using the given compressor +var decompress = function(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > compressorIDs.length) { + throw new Error( + 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + + compressorID + + ')' + ); + } + switch (compressorID) { + case compressorIDs.snappy: + Snappy.uncompress(compressedData, callback); + break; + case compressorIDs.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(null, compressedData); + } +}; + +module.exports = { + compressorIDs: compressorIDs, + uncompressibleCommands: uncompressibleCommands, + compress: compress, + decompress: decompress +}; diff --git a/node_modules/mongodb-core/lib/wireprotocol/shared.js b/node_modules/mongodb-core/lib/wireprotocol/shared.js new file mode 100644 index 0000000..96528cd --- /dev/null +++ b/node_modules/mongodb-core/lib/wireprotocol/shared.js @@ -0,0 +1,55 @@ +'use strict'; + +var ReadPreference = require('../topologies/read_preference'), + MongoError = require('../error').MongoError; + +var MESSAGE_HEADER_SIZE = 16; + +// OPCODE Numbers +// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes +var opcodes = { + OP_REPLY: 1, + OP_UPDATE: 2001, + OP_INSERT: 2002, + OP_QUERY: 2004, + OP_GETMORE: 2005, + OP_DELETE: 2006, + OP_KILL_CURSORS: 2007, + OP_COMPRESSED: 2012 +}; + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if (options.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoError('read preference must be a ReadPreference instance'); + } + + return readPreference; +}; + +// Parses the header of a wire protocol message +var parseHeader = function(message) { + return { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; +}; + +module.exports = { + getReadPreference: getReadPreference, + MESSAGE_HEADER_SIZE: MESSAGE_HEADER_SIZE, + opcodes: opcodes, + parseHeader: parseHeader +}; diff --git a/node_modules/mongodb-core/package.json b/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..ebb70de --- /dev/null +++ b/node_modules/mongodb-core/package.json @@ -0,0 +1,90 @@ +{ + "_from": "mongodb-core@3.1.8", + "_id": "mongodb-core@3.1.8", + "_inBundle": false, + "_integrity": "sha512-reWCqIRNehyuLaqaz5JMOmh3Xd8JIjNX34o8mnewXLK2Fyt/Ky6BZbU+X0OPzy8qbX+JZrOtnuay7ASCieTYZw==", + "_location": "/mongodb-core", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongodb-core@3.1.8", + "name": "mongodb-core", + "escapedName": "mongodb-core", + "rawSpec": "3.1.8", + "saveSpec": null, + "fetchSpec": "3.1.8" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.8.tgz", + "_shasum": "696cd5581c17d4f44f911b9cd089239e3e687b0e", + "_spec": "mongodb-core@3.1.8", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb", + "author": { + "name": "Christian Kvalheim" + }, + "bugs": { + "url": "https://github.com/mongodb-js/mongodb-core/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bson": "^1.1.0", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + }, + "deprecated": false, + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "devDependencies": { + "chai": "^4.1.2", + "chai-subset": "^1.6.0", + "co": "^4.6.0", + "eslint": "^4.6.1", + "eslint-plugin-prettier": "^2.2.0", + "jsdoc": "3.5.4", + "mongodb-extjson": "^2.1.2", + "mongodb-mock-server": "^1.0.0", + "mongodb-test-runner": "^1.1.18", + "prettier": "~1.12.0", + "sinon": "^6.0.0", + "snappy": "^6.1.1", + "standard-version": "^4.4.0" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb-js/mongodb-core", + "keywords": [ + "mongodb", + "core" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "mongodb-core", + "optionalDependencies": { + "saslprep": "^1.0.0" + }, + "peerOptionalDependencies": { + "kerberos": "^1.0.0", + "mongodb-extjson": "^2.1.2", + "snappy": "^6.1.1", + "bson-ext": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/mongodb-js/mongodb-core.git" + }, + "scripts": { + "atlas": "node ./test/atlas.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "coverage": "nyc node test/runner.js -t functional -l && node_modules/.bin/nyc report --reporter=text-lcov | node_modules/.bin/coveralls", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write index.js 'test/**/*.js' 'lib/**/*.js'", + "lint": "eslint index.js lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mongodb-test-runner -t 60000 test/tests" + }, + "version": "3.1.8" +} diff --git a/node_modules/mongodb/HISTORY.md b/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..0b4d45d --- /dev/null +++ b/node_modules/mongodb/HISTORY.md @@ -0,0 +1,2175 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) + + +### Bug Fixes + +* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) +* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) + + +### Features + +* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) + + + + +## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) + + +### Bug Fixes + +* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) + + +### Features + +* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) + + + + +## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) + + +### Features + +* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) + + + + +## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) + + +### Features + +* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) + + + + +## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) + + +### Bug Fixes + +* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) +* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) + + +### Features + +* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) + + + + +## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) +* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) +* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) +* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) +* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) + + +### Features + +* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) +* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) +* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) + + + + +## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) + + +### Features + +* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) + + + + +## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) +* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) +* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) +* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) +* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) +* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) +* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) +* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) + + +### Features + +* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) +* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) +* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) + + + + +## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) + + +### Bug Fixes + +* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) +* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) +* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) +* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) + + +### Features + +* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) + + + + +## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) +* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) + + +### Features + +* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) +* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) + + + + +## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) + + + + +## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) +* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) +* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) +* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) + + +### Features + +* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) +* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) + + + + +## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) + +* update mongodb-core to 3.0.1 + + +# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) + + +### Bug Fixes + +* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) +* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) + + +### Features + +* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) + + +### BREAKING CHANGES + +* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. + +Part of NODE-1089 +* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and +number `keepAliveInitialDelay` + +Fixes NODE-998 + + + + +# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) + + +### Bug Fixes + +* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) +* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) +* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) +* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) +* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) +* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) +* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) +* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) +* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) +* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) +* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) +* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) +* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) +* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) +* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) +* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) +* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) +* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) +* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) +* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) +* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) +* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) +* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) +* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) +* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) +* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) +* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) +* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) +* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) +* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) +* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) +* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) +* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) +* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) +* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) +* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) +* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) +* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) +* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) +* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) +* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) +* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) + + +### Features + +* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) +* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) +* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) +* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) +* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) +* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) +* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) +* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) +* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) +* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) +* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) +* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) +* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) +* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) +* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) +* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) +* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) +* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) +* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) + + +### BREAKING CHANGES + +* **aggregation:** If you use aggregation, and try to use the explain flag while you +have a readConcern or writeConcern, your query will fail +* **collection:** `find` and `findOne` no longer support the `fields` parameter. +You can achieve the same results as the `fields` parameter by +either using `Cursor.prototype.project`, or by passing the `projection` +property in on the `options` object. Additionally, `find` does not +support individual options like `skip` and `limit` as positional +parameters. You must pass in these parameters in the `options` object + + + +3.0.0 2017-??-?? +---------------- +* NODE-1043 URI-escaping authentication and hostname details in connection string + +2.2.31 2017-08-08 +----------------- +* update mongodb-core to 2.2.15 +* allow auth option in MongoClient.connect +* remove duplicate option `promoteLongs` from MongoClient's `connect` +* bulk operations should not throw an error on empty batch + +2.2.30 2017-07-07 +----------------- +* Update mongodb-core to 2.2.14 +* MongoClient + * add `appname` to list of valid option names + * added test for passing appname as option +* NODE-1052 ensure user options are applied while parsing connection string uris + +2.2.29 2017-06-19 +----------------- +* Update mongodb-core to 2.1.13 + * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. + * Use actual server type in standalone SDAM events. +* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). +* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). +* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. +* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. + +2.2.28 2017-06-02 +----------------- +* Update mongodb-core to 2.1.12 + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + * Minor fix to report the correct state on error. + * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). + * Fix require_optional loading of bson-ext. + * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. + * NODE-999 SDAM fixes for Mongos and single Server event emitting. + * NODE-1014 Set socketTimeout to default to 360 seconds. + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. + +2.2.27 2017-05-22 +----------------- +* Updated mongodb-core to 2.1.11 + * NODE-987 Clear out old intervalIds on when calling topologyMonitor. + * NODE-987 Moved filtering to pingServer method and added test case. + * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). + * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. +* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. +* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() +* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). +* NODE-996 Propegate all events up to a MongoClient instance. +* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). +* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. + +2.2.26 2017-04-18 +----------------- +* Updated mongodb-core to 2.1.10 + * NODE-981 delegate auth to replset/mongos if inTopology is set. + * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. + * Remove dynamic require (Issue #175, https://github.com/tellnes). + * NODE-696 Handle interrupted error for createIndexes. + * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. + * NODE-966 promoteValues not being promoted correctly to getMore. + * Merged in fix for flushing out monitoring operations. +* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). +* Mark group and profilingInfo as deprecated methods +* NODE-956 DOCS Examples. +* Update readable-stream to version 2.2.7. +* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. +* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) +* Fixed merging of writeConcerns on db.collection method. +* NODE-970 mix in readPreference for strict mode listCollections callback. +* NODE-966 added testcase for promoteValues being applied to getMore commands. +* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. +* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). +* NODE-963 Correctly handle cursor.count when using APM. + +2.2.25 2017-03-17 +----------------- +* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). +* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). +* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. +* Exposed BSONRegExp type. +* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). +* NODE-951 Added support for sslCRL option and added a test case for it. +* NODE-953 Made batchSize issue general at cursor level. +* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. +* Updated mongodb-core to 2.1.9. + * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. + * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. + * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. + * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. + * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.2.24 2017-02-14 +----------------- +* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. + +2.2.23 2017-02-13 +----------------- +* Updated mongodb-core to 2.1.8. + * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. + * NODE-927 fixes issue where authentication was performed against arbiter instances. + * NODE-915 Normalize all host names to avoid comparison issues. + * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. +* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. +* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects +* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) + +2.2.22 2017-01-24 +----------------- +* Updated mongodb-core to 2.1.7. + * NODE-919 ReplicaSet connection does not close immediately (Issue #156). + * NODE-901 Fixed bug when normalizing host names. + * NODE-909 Fixed readPreference issue caused by direct connection to primary. + * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. +* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) + +2.2.21 2017-01-13 +----------------- +* Updated mongodb-core to 2.1.6. + * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.2.20 2017-01-11 +----------------- +* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. + +2.2.19 2017-01-03 +----------------- +* Corrupted Npm release fix. + +2.2.18 2017-01-03 +----------------- +* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. + +2.2.17 2017-01-02 +----------------- +* updated createCollection doc options and linked to create command. +* Updated mongodb-core to 2.1.3. + * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining + * Moved replicaset monitoring away from serial mode and to parallel mode. + * updated bson and bson-ext dependencies to 1.0.2. + +2.2.16 2016-12-13 +----------------- +* NODE-899 reversed upsertedId change to bring back old behavior. + +2.2.15 2016-12-10 +----------------- +* Updated mongodb-core to 2.1.2. + * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. + * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). + +2.2.14 2016-12-08 +----------------- +* Updated mongodb-core to 2.1.1. +* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. + +2.2.13 2016-12-05 +----------------- +* Updated mongodb-core to 2.1.0. +* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. +* Expose parserType as property on topology objects. + +2.2.12 2016-11-29 +----------------- +* Updated mongodb-core to 2.0.14. + * Updated bson library to 0.5.7. + * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). + * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). + * Only check isConnected against availableConnections (Issue #142). + * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. + * Set default servername to host is not passed through for sni. + * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). + * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. + * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. + * NODE-850 Update Max Staleness implementation. + * NODE-849 username no longer required for MONGODB-X509 auth. + * NODE-848 BSON Regex flags must be alphabetically ordered. + * NODE-846 Create notice for all third party libraries. + * NODE-843 Executing bulk operations overwrites write concern parameter. + * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. + * NODE-840 Resync CRUD spec tests. + * Unescapable while(true) loop (Issue #152). +* NODE-864 close event not emits during network issues using single server topology. +* Introduced maxStalenessSeconds. +* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. +* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). + +2.2.11 2016-10-21 +----------------- +* Updated mongodb-core to 2.0.13. + - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). + - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). + - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). + - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). +* NODE-824, readPreference "nearest" does not work when specified at collection level. +* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. +* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. +* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. + +2.2.10 2016-09-15 +----------------- +* Updated mongodb-core to 2.0.12. +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. +* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. +* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. +* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. +* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. + +2.2.9 2016-08-29 +---------------- +* Updated mongodb-core to 2.0.11. +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. +* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). + +2.2.8 2016-08-23 +---------------- +* Updated mongodb-core to 2.0.10. +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.2.7 2016-08-19 +---------------- +* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). +* Updated mongodb-core to 2.0.9. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.2.6 2016-08-16 +---------------- +* Updated mongodb-core to 2.0.8. +* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Enable maxTimeMS in count, distinct, findAndModify. + +2.2.5 2016-07-28 +---------------- +* Updated mongodb-core to 2.0.7. +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. + +2.2.4 2016-07-19 +---------------- +* NPM corrupted upload fix. + +2.2.3 2016-07-19 +---------------- +* Updated mongodb-core to 2.0.6. +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.2.2 2016-07-15 +---------------- +* Updated mongodb-core to 2.0.5. +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.2.1 2016-07-11 +---------------- +* Updated mongodb-core to 2.0.4. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.2.0 2016-07-05 +---------------- +* Updated mongodb-core to 2.0.3. +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. +* Fixed logger error serialization issue. +* Documentation fixes. +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.1.21 2016-05-30 +----------------- +* Updated mongodb-core to 1.3.21. +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +2.1.20 2016-05-25 +----------------- +* Refactored MongoClient options handling to simplify the logic, unifying it. +* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Updated mongodb-core to 1.3.20. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +2.1.19 2016-05-17 +---------------- +* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +* Ensure replicaset topology destroy is never called by SDAM. +* Ensure all paths are correctly returned on inspectServer in replset. +* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. + +2.1.18 2016-04-27 +----------------- +* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. + +2.1.17 2016-04-26 +----------------- +* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. +* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. +* Fix timeout issue using new flags #1361. +* Updated mongodb-core to 1.3.17. +* Better handling of unique createIndex error. +* Emit error only if db instance has an error listener. +* DEFAULT authMechanism; don't throw error if explicitly set by user. + +2.1.16 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.16. + +2.1.15 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.15. +* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +2.1.14 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.13. +* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +2.1.13 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.12. + +2.1.12 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.11. +* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. +* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. +* isConnected method for mongos uses same selection code as getServer. +* Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +2.1.11 2016-03-23 +----------------- +* Updated mongodb-core to 1.3.10. +* Introducing simplified connections settings. + +2.1.10 2016-03-21 +----------------- +* Updated mongodb-core to 1.3.9. +* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) +* Forwards SDAM monitoring events from mongodb-core. + +2.1.9 2016-03-16 +---------------- +* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. +* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. + +2.1.8 2016-03-14 +---------------- +* Updated mongodb-core to 1.3.5. +* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. +* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +* Ensure RequestId can never be larger than Max Number integer size. +* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. +* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). +* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. +* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. +* NODE-663 added lookup helper on aggregation cursor. +* NODE-585 Result object specified incorrectly for findAndModify?. +* NODE-666 harden validation for findAndModify CRUD methods. + +2.1.7 2016-02-09 +---------------- +* NODE-656 fixed corner case where cursor count command could be left without a connection available. +* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. +* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). +* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). +* NODE-657 insertOne don`t return promise in some cases. +* Added destroy alias for abort function on GridFSBucketWriteStream. + +2.1.6 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/node_modules/mongodb/LICENSE.md b/node_modules/mongodb/LICENSE.md new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/node_modules/mongodb/Readme.md b/node_modules/mongodb/Readme.md index 5e4877d..596708c 100644 --- a/node_modules/mongodb/Readme.md +++ b/node_modules/mongodb/Readme.md @@ -1,23 +1,31 @@ +[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** + ## MongoDB Node.JS Driver - + | what | where | |---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| documentation | http://mongodb.github.io/node-mongodb-native | +| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | | source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) -- Valeri Karpov [@code_barbarian](https://twitter.com/code_barbarian) +| mongodb | http://www.mongodb.org | ### Bugs / Feature Requests -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a case in our issue management tool, JIRA: -- Create an account and login . -- Navigate to the NODE project . +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). - Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the @@ -25,394 +33,461 @@ Core Server (i.e. SERVER) project are **public**. ### Questions and Bug Reports - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ + * Mailing List: [groups.google.com/forum/#!forum/node-mongodb-native](https://groups.google.com/forum/#!forum/node-mongodb-native) + * JIRA: [jira.mongodb.org](http://jira.mongodb.org) ### Change Log -http://jira.mongodb.org/browse/NODE +Change history can be found in [`HISTORY.md`](HISTORY.md). + +# Installation -## Install +The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. -To install the most recent release from npm, run: +## MongoDB Driver - npm install mongodb +Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. -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) +```bash +npm install mongodb --save +``` -To install the latest from the repository, run:: +This will download the MongoDB driver and add a dependency entry in your `package.json` file. - npm install path/to/node-mongodb-native +You can also use the [Yarn](https://yarnpkg.com/en) package manager. -## Live Examples - +## Troubleshooting -## Introduction +The MongoDB driver depends on several other packages. These are: -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/. +* [mongodb-core](https://github.com/mongodb-js/mongodb-core) +* [bson](https://github.com/mongodb/js-bson) +* [kerberos](https://github.com/mongodb-js/kerberos) +* [node-gyp](https://github.com/nodejs/node-gyp) -A simple example of inserting a document. +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; +**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; +### Diagnosing on UNIX - var collection = db.collection('test_insert'); - collection.insert({a:2}, function(err, docs) { - - collection.count(function(err, count) { - console.log(format("count = %s", count)); - }); +If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - // Locate all the entries using find - collection.find().toArray(function(err, results) { - console.dir(results); - // Let's close the db - db.close(); - }); - }); - }) +```bash +git clone https://github.com/mongodb-js/kerberos +cd kerberos +npm install ``` -## Data types +If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: -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). +```bash +npm install -g node-gyp +``` + +If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. -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: +```bash +cd yourproject +npm install mongodb --save +``` -```javascript - // Get the objectID type - var ObjectID = require('mongodb').ObjectID; +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - var idString = '4e4e1638c85e808431000003'; - collection.findOne({_id: new ObjectID(idString)}, console.log) // ok - collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined +```bash +npm --loglevel verbose install mongodb ``` -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 +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A compiler tool chain known to work for compiling `kerberos` on Windows is the following. + +* Visual Studio C++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. + +```bash +npm install -g node-gyp ``` -### The C/C++ bson parser/serializer +Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: + +```bash +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues -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 +Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). -```javascript - // using native_parser: - MongoClient.connect('mongodb://127.0.0.1:27017/test' - , {db: {native_parser: true}}, function(err, db) {}) +Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myproject +cd myproject ``` -The C++ parser uses the js objects both for serialization and deserialization. +Enter the following command and answer the questions to create the initial structure for your new project: -## GitHub information +```bash +npm init +``` -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. +Next, install the driver dependency. -Once you have the source you can test the driver by running +```bash +npm install mongodb --save +``` - $ node test/runner.js -t functional +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. -in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass. +### Start a MongoDB Server -## Examples +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). -For examples look in the examples/ directory. You can execute the examples using node. +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a ``mongod`` process. - $ cd examples - $ node queries.js +```bash +mongod --dbpath=/data +``` -## GridStore +You should see the **mongod** process start up and print some status information. -The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition. +### Connect to MongoDB -For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md) +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. -## Replicasets +Add code to connect to the server and the database **myproject**: -For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -### Primary Key Factories +// Connection URL +const url = 'mongodb://localhost:27017'; -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". +// Database Name +const dbName = 'myproject'; -Simple example below +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; + const db = client.db(dbName); - // Custom factory (need to provide a 12 byte array); - CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } + client.close(); +}); +``` - MongoClient.connect('mongodb://127.0.0.1:27017/test', {'pkFactory':CustomPKFactory}, function(err, db) { - if(err) throw err; +Run your app from the command line with: - db.dropDatabase(function(err, done) { - - db.createCollection('test_custom_key', function(err, collection) { - - collection.insert({'a':1}, function(err, docs) { - - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { - console.dir(items); - // Let's close the db - db.close(); - }); - }); - }); - }); +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(result); }); +} ``` -## Documentation +The **insert** command returns an object with the following fields: -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. +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert -### Find +Add the following code to call the **insertDocuments** function: -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`. +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -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. +// Connection URL +const url = 'mongodb://localhost:27017'; -Signatures: +// Database Name +const dbName = 'myproject'; -```javascript - var cursor = collection.find(query, [fields], options); - cursor.sort(fields).limit(n).skip(m). +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); - cursor.nextObject(function(err, doc) {}); - cursor.each(function(err, doc) {}); - cursor.toArray(function(err, docs) {}); + const db = client.db(dbName); - cursor.rewind() // reset the cursor to its initial state. + insertDocuments(db, function() { + client.close(); + }); +}); ``` -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 MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db - .collection('test') - .find({}) - .limit(10) - .toArray(function(err, docs) { - console.dir(docs); - }); - }); +Run the updated **app.js** file: + +```bash +node app.js ``` -### Insert +The operation returns the following output: + +```bash +Connected successfully to server +Inserted 3 documents into the collection +``` -Signature: +### Find All Documents -```javascript - collection.insert(docs, options, [callback]); +Add a query that returns all the documents. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs) + callback(docs); + }); +} ``` -where `docs` can be a single document or an array of documents. +This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -Useful options: +// Connection URL +const url = 'mongodb://localhost:27017'; -* `w:1` Should always set if you have a callback. +// Database Name +const dbName = 'myproject'; -See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected correctly to server"); -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; + const db = client.db(dbName); - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) { - if (err) console.warn(err.message); - if (err && err.message.indexOf('E11000 ') !== -1) { - // this _id was already inserted in the database - } + insertDocuments(db, function() { + findDocuments(db, function() { + client.close(); }); }); +}); ``` -Note that there's no reason to pass a callback to the insert or update commands -unless you use the `w:1` option. If you don't specify `w:1`, then -your callback will be called immediately. +### Find Documents with a Query Filter -### Update: update and insert (upsert) +Add a query filter to find only documents which meet the query criteria. -The update operation will update the first document that matches your query -(or all documents that match if you use `multi:true`). -If `w:1`, `upsert` is not set, and no documents match, your callback will return 0 documents updated. +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(docs); + }); +} +``` -See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for -the modifier (`$inc`, `$set`, `$push`, etc.) formats. +Only the documents which match ``'a' : 3`` should be returned. -Signature: +### Update a document -```javascript - collection.update(criteria, objNew, options, [callback]); +The following operation updates a document in the **documents** collection. + +```js +const updateDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} ``` -Useful options: +The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. -* `w:1` 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. +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -Example for `update`: +// Connection URL +const url = 'mongodb://localhost:27017'; -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; +// Database Name +const dbName = 'myproject'; - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); - db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) { - if (err) console.warn(err.message); - else console.log('successfully updated'); + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + client.close(); }); }); +}); ``` -### 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: +### Remove a document - 1. The signatures differ. - 2. You can only findAndModify a single item, not multiple items. +Remove the document where the field **a** is equal to **3**. -Signature: - -```javascript - collection.findAndModify(query, sort, update, options, callback) +```js +const removeDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} ``` -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). +Add the new method to the **MongoClient.connect** callback function. -See the -[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) -for more details. +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -Useful options: +// Connection URL +const url = 'mongodb://localhost:27017'; -* `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. +// Database Name +const dbName = 'myproject'; -Example for `findAndModify`: +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; + const db = client.db(dbName); - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - db.collection('test').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. + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + client.close(); + }); }); }); +}); ``` -### Save +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexCollection = function(db, callback) { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); +}; +``` -The `save` method is a shorthand for upsert if the document contains an -`_id`, or an insert if there is no `_id`. +Add the ``indexCollection`` method to your app: -## Release Notes +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); -See HISTORY +// Connection URL +const url = 'mongodb://localhost:27017'; -## Credits +const dbName = 'myproject'; -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) +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); -## Contributors + const db = client.db(dbName); -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 + insertDocuments(db, function() { + indexCollection(db, function() { + client.close(); + }); + }); +}); +``` -## License +For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - Copyright 2009 - 2013 MongoDb Inc. +## Next Steps - 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 + * [MongoDB Documentation](http://mongodb.org) + * [Read about Schemas](http://learnmongodbthehardway.com) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - http://www.apache.org/licenses/LICENSE-2.0 +## License - 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. +[Apache 2.0](LICENSE.md) +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/node_modules/mongodb/index.js b/node_modules/mongodb/index.js index 4f59e9d..fe305d6 100644 --- a/node_modules/mongodb/index.js +++ b/node_modules/mongodb/index.js @@ -1 +1,67 @@ -module.exports = require('./lib/mongodb'); +'use strict'; + +// Core module +const core = require('mongodb-core'); +const Instrumentation = require('./lib/apm'); + +// Set up the connect function +const connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; +connect.MongoNetworkError = core.MongoNetworkError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/topologies/server'); +connect.ReplSet = require('./lib/topologies/replset'); +connect.Mongos = require('./lib/topologies/mongos'); +connect.ReadPreference = require('mongodb-core').ReadPreference; +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.AggregationCursor = require('./lib/aggregation_cursor'); +connect.CommandCursor = require('./lib/command_cursor'); +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = require('mongodb-core').Server; +connect.CoreConnection = require('mongodb-core').Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.BSONRegExp = core.BSON.BSONRegExp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const instrumentation = new Instrumentation(); + instrumentation.instrument(connect.MongoClient, callback); + return instrumentation; +}; + +// Set our exports to be the connect function +module.exports = connect; diff --git a/node_modules/mongodb/lib/admin.js b/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..8fb4cac --- /dev/null +++ b/node_modules/mongodb/lib/admin.js @@ -0,0 +1,293 @@ +'use strict'; + +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; + +const addUser = require('./operations/db_ops').addUser; +const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; +const removeUser = require('./operations/db_ops').removeUser; +const replSetGetStatus = require('./operations/admin_ops').replSetGetStatus; +const serverStatus = require('./operations/admin_ops').serverStatus; +const validateCollection = require('./operations/admin_ops').validateCollection; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +function Admin(db, topology, promiseLibrary) { + if (!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db, + topology: topology, + promiseLibrary: promiseLibrary + }; +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + command, + options, + callback + ]); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Retrieve this db's server status. + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, serverStatus, [this, options, callback]); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { ping: 1 }; + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name to admin + options.dbName = 'admin'; + + return executeOperation(this.s.db.s.topology, addUser, [ + this.s.db, + username, + password, + options, + callback + ]); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name + options.dbName = 'admin'; + + return executeOperation(this.s.db.s.topology, removeUser, [ + this.s.db, + username, + options, + callback + ]); +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, validateCollection, [ + this, + collectionName, + options, + callback + ]); +}; + +/** + * List the available databases + * + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { listDatabases: 1 }; + if (options.nameOnly) cmd.nameOnly = Number(cmd.nameOnly); + return executeOperation(this.s.db.s.topology, executeDbAdminCommand.bind(this.s.db), [ + this.s.db, + cmd, + options, + callback + ]); +}; + +/** + * Get ReplicaSet status + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.db.s.topology, replSetGetStatus, [this, options, callback]); +}; + +module.exports = Admin; diff --git a/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..e1bff13 --- /dev/null +++ b/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,407 @@ +'use strict'; + +const inherits = require('util').inherits; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('./cursor'); + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology Options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Optional ClientSession + session: options.session + }; +}; + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Extend the Cursor +for (var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if (this.s.state === AggregationCursor.CLOSED || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + if (typeof value !== 'number') + throw MongoError.create({ message: 'batchSize requires an integer', drvier: true }); + if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({ $geoNear: document }); + return this; +}; + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({ $group: document }); + return this; +}; + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({ $limit: value }); + return this; +}; + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({ $match: document }); + return this; +}; + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if (this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +}; + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({ $out: destination }); + return this; +}; + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({ $project: document }); + return this; +}; + +/** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.lookup = function(document) { + this.s.cmd.pipeline.push({ $lookup: document }); + return this; +}; + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({ $redact: document }); + return this; +}; + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({ $skip: value }); + return this; +}; + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({ $sort: document }); + return this; +}; + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({ $unwind: field }); + return this; +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +AggregationCursor.prototype.getLogger = function() { + return this.logger; +}; + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function AggregationCursor.prototype.hasNext + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/node_modules/mongodb/lib/apm.js b/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..f78e4aa --- /dev/null +++ b/node_modules/mongodb/lib/apm.js @@ -0,0 +1,31 @@ +'use strict'; +const EventEmitter = require('events').EventEmitter; + +class Instrumentation extends EventEmitter { + constructor() { + super(); + } + + instrument(MongoClient, callback) { + // store a reference to the original functions + this.$MongoClient = MongoClient; + const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); + + const instrumentation = this; + MongoClient.prototype.connect = function(callback) { + this.s.options.monitorCommands = true; + this.on('commandStarted', event => instrumentation.emit('started', event)); + this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); + this.on('commandFailed', event => instrumentation.emit('failed', event)); + return $prototypeConnect.call(this, callback); + }; + + if (typeof callback === 'function') callback(null, this); + } + + uninstrument() { + this.$MongoClient.prototype.connect = this.$prototypeConnect; + } +} + +module.exports = Instrumentation; diff --git a/node_modules/mongodb/lib/authenticate.js b/node_modules/mongodb/lib/authenticate.js new file mode 100644 index 0000000..35c92b4 --- /dev/null +++ b/node_modules/mongodb/lib/authenticate.js @@ -0,0 +1,136 @@ +'use strict'; + +var shallowClone = require('./utils').shallowClone, + handleCallback = require('./utils').handleCallback, + MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var authenticate = function(client, username, password, options, callback) { + // Did the user destroy the topology + if (client.topology && client.topology.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.dbName; + authdb = options.authdb ? options.authdb : authdb; + authdb = options.authSource ? options.authSource : authdb; + + // Callback + var _callback = function(err, result) { + if (client.listeners('authenticated').length > 0) { + client.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + }; + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if (authMechanism === 'MONGODB-CR') { + client.topology.auth('mongocr', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'PLAIN') { + client.topology.auth('plain', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'MONGODB-X509') { + client.topology.auth('x509', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'SCRAM-SHA-1') { + client.topology.auth('scram-sha-1', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'SCRAM-SHA-256') { + client.topology.auth('scram-sha-256', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if (authMechanism === 'GSSAPI') { + if (process.platform === 'win32') { + client.topology.auth('sspi', authdb, username, password, options, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + client.topology.auth('gssapi', authdb, username, password, options, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if (authMechanism === 'DEFAULT') { + client.topology.auth('default', authdb, username, password, function(err) { + if (err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback( + callback, + MongoError.create({ + message: f('authentication mechanism %s not supported', options.authMechanism), + driver: true + }) + ); + } +}; + +module.exports = function(self, username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if (!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if ( + options.authMechanism !== 'GSSAPI' && + options.authMechanism !== 'DEFAULT' && + options.authMechanism !== 'MONGODB-CR' && + options.authMechanism !== 'MONGODB-X509' && + options.authMechanism !== 'SCRAM-SHA-1' && + options.authMechanism !== 'SCRAM-SHA-256' && + options.authMechanism !== 'PLAIN' + ) { + return handleCallback( + callback, + MongoError.create({ + message: + 'only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism', + driver: true + }) + ); + } + + // If we have a callback fallback + if (typeof callback === 'function') + return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; + // Reject error + if (err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new self.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if (err && err.message && err.message.indexOf('saslStart') !== -1) err.code = 59; + // Reject error + if (err) return reject(err); + resolve(r); + }); + }); +}; diff --git a/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..c6354bb --- /dev/null +++ b/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,1105 @@ +'use strict'; + +const Long = require('mongodb-core').BSON.Long; +const MongoError = require('mongodb-core').MongoError; +const toError = require('../utils').toError; +const handleCallback = require('../utils').handleCallback; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const ObjectID = require('mongodb-core').BSON.ObjectID; +const BSON = require('mongodb-core').BSON; + +// Error codes +const UNKNOWN_ERROR = 8; +const INVALID_BSON_ERROR = 22; +const WRITE_CONCERN_ERROR = 64; +const MULTIPLE_ERROR = 65; + +// Insert types +const INSERT = 1; +const UPDATE = 2; +const REMOVE = 3; + +const bson = new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp +]); + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +class LegacyOp { + constructor(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; + } +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {BulkWriteResult} a BulkWriteResult instance + */ +class BulkWriteResult { + constructor(bulkResult) { + this.result = bulkResult; + } + + /** + * @return {boolean} ok Did bulk operation correctly execute + */ + get ok() { + return this.result.ok; + } + + /** + * @return {number} nInserted number of inserted documents + */ + get nInserted() { + return this.result.nInserted; + } + + /** + * @return {number} nUpserted Number of upserted documents + */ + get nUpserted() { + return this.result.nUpserted; + } + + /** + * @return {number} nMatched Number of matched documents + */ + get nMatched() { + return this.result.nMatched; + } + + /** + * @return {number} nModified Number of documents updated physically on disk + */ + get nModified() { + return this.result.nModified; + } + + /** + * @return {number} nRemoved Number of removed documents + */ + get nRemoved() { + return this.result.nRemoved; + } + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + getInsertedIds() { + return this.result.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + getUpsertedIds() { + return this.result.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + getRawResponse() { + return this.result; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @param {number} index of the write error to return, returns null if there is no result for passed in index + * @return {WriteError} + */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + getWriteErrors() { + return this.result.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + getLastOp() { + return this.result.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return null; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); + } + } + + /** + * @return {BulkWriteResult} a BulkWriteResult instance + */ + toJSON() { + return this.result; + } + + /** + * @return {string} + */ + toString() { + return `BulkWriteResult(${this.toJSON(this.result)})`; + } + + /** + * @return {boolean} + */ + isOk() { + return this.result.ok === 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {WriteConcernError} a WriteConcernError instance + */ +class WriteConcernError { + constructor(err) { + this.err = err; + } + + /** + * @return {number} code Write concern error code. + */ + get code() { + return this.err.code; + } + + /** + * @return {string} errmsg Write concern error message. + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, errmsg: this.err.errmsg }; + } + + /** + * @return {string} + */ + toString() { + return `WriteConcernError(${this.err.errmsg})`; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @return {WriteConcernError} a WriteConcernError instance + */ +class WriteError { + constructor(err) { + this.err = err; + } + + /** + * @return {number} code Write concern error code. + */ + get code() { + return this.err.code; + } + + /** + * @return {number} index Write concern error original bulk operation index. + */ + get index() { + return this.err.index; + } + + /** + * @return {string} errmsg Write concern error message. + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * Define access methods + * @return {object} + */ + getOperation() { + return this.err.op; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + /** + * @return {string} + */ + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +function mergeBatchResults(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } else if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if (bulkResult.lastOp) { + lastOpTS = + typeof bulkResult.lastOp.ts === 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) + : bulkResult.lastOp.ts; + lastOpT = + typeof bulkResult.lastOp.t === 'number' + ? Long.fromNumber(bulkResult.lastOp.t) + : bulkResult.lastOp.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if (batch.batchType === INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (batch.batchType === REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (batch.batchType === UPDATE && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index, + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +/** + * handles write concern error + * + * @param {object} batch + * @param {object} bulkResult + * @param {boolean} ordered + * @param {WriteConcernError} err + * @param {function} callback + */ +function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) { + mergeBatchResults(ordered, batch, bulkResult, null, err.result); + + const wrappedWriteConcernError = new WriteConcernError({ + errmsg: err.result.writeConcernError.errmsg, + code: err.result.writeConcernError.result + }); + return handleCallback( + callback, + new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), + null + ); +} + +/** + * Creates a new BulkWriteError + * + * @class + * @param {Error|string|object} message The error message + * @param {BulkWriteResult} result The result of the bulk write operation + * @return {BulkWriteError} A BulkWriteError instance + * @extends {MongoError} + */ +class BulkWriteError extends MongoError { + constructor(error, result) { + const message = error.err || error.errmsg || error.errMessage || error; + super(message); + + Object.assign(this, error); + + this.name = 'BulkWriteError'; + this.result = result; + } +} + +/** + * Handles the find operators for the bulk operations + * @class + */ +class FindOperators { + /** + * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation + */ + constructor(bulkOperation) { + this.s = bulkOperation.s; + } + + /** + * Add a single update document to the bulk operation + * + * @method + * @param {object} updateDocument update operations + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + update(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: true, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} updateDocument update operations + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + updateOne(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: false, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} updateDocument the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + replaceOne(updateDocument) { + this.updateOne(updateDocument); + } + + /** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperators} + */ + upsert() { + this.s.currentOp.upsert = true; + return this; + } + + /** + * Add a delete one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + deleteOne() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 1 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * Add a delete operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + delete() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 0 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * backwards compatability for deleteOne + */ + removeOne() { + return this.deleteOne(); + } + + /** + * backwards compatability for delete + */ + remove() { + return this.delete(); + } +} + +/** + * Parent class to OrderedBulkOperation and UnorderedBulkOperation + * @class + */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation|UnordedBulkOperation} + */ + constructor(topology, collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.collectionName; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + const bson = topology.bson; + + // Set max byte size + const isMaster = topology.lastIsMaster(); + const maxBatchSizeBytes = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); + const writeConcern = finalOptions.writeConcern; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult, + // Current batch state + currentBatch: null, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: null, + currentUpdateBatch: null, + currentRemoveBatch: null, + batches: [], + // Write concern + writeConcern: writeConcern, + // Max batch size options + maxBatchSizeBytes: maxBatchSizeBytes, + maxWriteBatchSize: maxWriteBatchSize, + // Namespace + namespace: namespace, + // BSON + bson: bson, + // Topology + topology: topology, + // Options + options: finalOptions, + // Current operation + currentOp: currentOp, + // Executed + executed: executed, + // Collection + collection: collection, + // Promise Library + promiseLibrary: promiseLibrary, + // Fundamental error + err: null, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @param {object} document the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + insert(document) { + if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) + document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, document); + } + + /** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + */ + find(selector) { + if (!selector) { + throw toError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** + * Raw performs the bulk operation + * + * @method + * @param {object} op operation + * @return {OrderedBulkOperation|UnorderedBulkOperation} + */ + raw(op) { + const key = Object.keys(op)[0]; + + // Set up the force server object id + const forceServerObjectId = + typeof this.s.options.forceServerObjectId === 'boolean' + ? this.s.options.forceServerObjectId + : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if ( + (op.updateOne && op.updateOne.q) || + (op.updateMany && op.updateMany.q) || + (op.replaceOne && op.replaceOne.q) + ) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return this.s.options.addToOperationsList(this, UPDATE, op[key]); + } + + // Crud spec update format + if (op.updateOne || op.updateMany || op.replaceOne) { + const multi = op.updateOne || op.replaceOne ? false : true; + const operation = { + q: op[key].filter, + u: op[key].update || op[key].replacement, + multi: multi + }; + if (this.isOrdered) { + operation.upsert = op[key].upsert ? true : false; + if (op.collation) operation.collation = op.collation; + } else { + if (op[key].upsert) operation.upsert = true; + } + if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; + return this.s.options.addToOperationsList(this, UPDATE, operation); + } + + // Remove operations + if ( + op.removeOne || + op.removeMany || + (op.deleteOne && op.deleteOne.q) || + (op.deleteMany && op.deleteMany.q) + ) { + op[key].limit = op.removeOne ? 1 : 0; + return this.s.options.addToOperationsList(this, REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if (op.deleteOne || op.deleteMany) { + const limit = op.deleteOne ? 1 : 0; + const operation = { q: op[key].filter, limit: limit }; + if (this.isOrdered) { + if (op.collation) operation.collation = op.collation; + } + return this.s.options.addToOperationsList(this, REMOVE, operation); + } + + // Insert operations + if (op.insertOne && op.insertOne.document == null) { + if (forceServerObjectId !== true && op.insertOne._id == null) + op.insertOne._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne); + } else if (op.insertOne && op.insertOne.document) { + if (forceServerObjectId !== true && op.insertOne.document._id == null) + op.insertOne.document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); + } + + if (op.insertMany) { + for (let i = 0; i < op.insertMany.length; i++) { + if (forceServerObjectId !== true && op.insertMany[i]._id == null) + op.insertMany[i]._id = new ObjectID(); + this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError( + 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' + ); + } + + /** + * Execute next write command in a chain + * + * @method + * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation + * @param {object} writeConcern + * @param {object} options + * @param {function} callback + */ + bulkExecute(_writeConcern, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.s.executed) { + const executedError = toError('batch cannot be re-executed'); + return typeof callback === 'function' + ? callback(executedError, null) + : this.s.promiseLibrary.reject(executedError); + } + + if (typeof _writeConcern === 'function') { + callback = _writeConcern; + } else if (_writeConcern && typeof _writeConcern === 'object') { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = toError('Invalid Operation, no operations specified'); + return typeof callback === 'function' + ? callback(emptyBatchError, null) + : this.s.promiseLibrary.reject(emptyBatchError); + } + return { options, callback }; + } + + /** + * Handles final options before executing command + * + * @param {object} config + * @param {object} config.options + * @param {number} config.batch + * @param {function} config.resultHandler + * @param {function} callback + */ + finalOptionsHandler(config, callback) { + const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); + if (this.s.writeConcern != null) { + finalOptions.writeConcern = this.s.writeConcern; + } + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (this.operationId) { + config.resultHandler.operationId = this.operationId; + } + + // Serialize functions + if (this.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true; + } + + // Ignore undefined + if (this.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true; + } + + // Is the bypassDocumentValidation options specific + if (this.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (this.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (config.batch.batchType === UPDATE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); + } + + if (config.batch.batchType === REMOVE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); + } + } + + try { + if (config.batch.batchType === INSERT) { + this.s.topology.insert( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === UPDATE) { + this.s.topology.update( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === REMOVE) { + this.s.topology.remove( + this.s.collection.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback( + callback, + null, + mergeBatchResults(false, config.batch, this.s.bulkResult, err, null) + ); + } + } + + /** + * Handles the write error before executing commands + * + * @param {function} callback + * @param {BulkWriteResult} writeResult + * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + if (this.s.bulkResult.writeErrors.length === 1) { + handleCallback( + callback, + new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), + null + ); + return true; + } + + handleCallback( + callback, + new BulkWriteError( + toError({ + message: 'write operation failed', + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }), + writeResult + ), + null + ); + return true; + } else if (writeResult.getWriteConcernError()) { + handleCallback( + callback, + new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), + null + ); + return true; + } + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// Exports symbols +module.exports = { + Batch, + BulkOperationBase, + BulkWriteError, + BulkWriteResult, + bson, + FindOperators, + handleMongoWriteConcernError, + LegacyOp, + mergeBatchResults, + INVALID_BSON_ERROR: INVALID_BSON_ERROR, + MULTIPLE_ERROR: MULTIPLE_ERROR, + UNKNOWN_ERROR: UNKNOWN_ERROR, + WRITE_CONCERN_ERROR: WRITE_CONCERN_ERROR, + INSERT: INSERT, + UPDATE: UPDATE, + REMOVE: REMOVE, + WriteError, + WriteConcernError +}; diff --git a/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..95722b3 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,178 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const utils = require('../utils'); +const toError = utils.toError; +const handleCallback = utils.handleCallback; +const BulkWriteResult = common.BulkWriteResult; +const Batch = common.Batch; +const mergeBatchResults = common.mergeBatchResults; +const executeOperation = utils.executeOperation; +const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; +const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; +const bson = common.bson; + +/** + * Add to internal list of Operations + * + * @param {OrderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {OrderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false + }); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatchSizeBytes + bulkOperation.s.currentBatchSizeBytes >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Reset the current size trackers + bulkOperation.s.currentBatchSize = 0; + bulkOperation.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + bulkOperation.s.currentBatchSize = bulkOperation.s.currentBatchSize + 1; + bulkOperation.s.currentBatchSizeBytes = bulkOperation.s.currentBatchSizeBytes + bsonSize; + } + + if (docType === common.INSERT) { + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.currentIndex, + _id: document._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } else { + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatchSizeBytes = bulkOperation.s.currentBatchSizeBytes + bsonSize; + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + } + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ + +class OrderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, true); + } + + /** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + options = ret.options; + callback = ret.callback; + + return executeOperation(this.s.topology, executeCommands, [this, options, callback]); + } +} + +/** + * Execute next write command in a chain + * + * @param {OrderedBulkOperation} bulkOperation + * @param {object} options + * @param {function} callback + */ +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + // Ordered execution of the command + const batch = bulkOperation.s.batches.shift(); + + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, true, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(true, batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return handleCallback(callback, null, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeOrderedBulkOp(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..0ff7473 --- /dev/null +++ b/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,202 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const utils = require('../utils'); +const toError = utils.toError; +const handleCallback = utils.handleCallback; +const BulkWriteResult = common.BulkWriteResult; +const Batch = common.Batch; +const mergeBatchResults = common.mergeBatchResults; +const executeOperation = utils.executeOperation; +const MongoWriteConcernError = require('mongodb-core').MongoWriteConcernError; +const handleMongoWriteConcernError = require('./common').handleMongoWriteConcernError; +const bson = common.bson; + +/** + * Add to internal list of Operations + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {UnorderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + // Holds the current batch + bulkOperation.s.currentBatch = null; + // Get the right type of batch + if (docType === common.INSERT) { + bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; + } else if (docType === common.UPDATE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatch.sizeBytes + bsonSize >= bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } else { + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if (docType === common.INSERT) { + bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.bulkResult.insertedIds.length, + _id: document._id + }); + } else if (docType === common.UPDATE) { + bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; + } + + // Update current batch size + bulkOperation.s.currentBatch.size = bulkOperation.s.currentBatch.size + 1; + bulkOperation.s.currentBatch.sizeBytes = bulkOperation.s.currentBatch.sizeBytes + bsonSize; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +class UnorderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, false); + } + + /** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + options = ret.options; + callback = ret.callback; + + return executeOperation(this.s.topology, executeBatches, [this, options, callback]); + } +} + +/** + * Execute the command + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {object} batch + * @param {object} options + * @param {function} callback + */ +function executeBatch(bulkOperation, batch, options, callback) { + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback); + } + handleCallback( + callback, + null, + mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result) + ); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * Execute all the commands + * + * @param {UnorderedBulkOperation} bulkOperation + * @param {object} options + * @param {function} callback + */ +function executeBatches(bulkOperation, options, callback) { + let numberOfCommandsToExecute = bulkOperation.s.batches.length; + // Execute over all the batches + for (let i = 0; i < bulkOperation.s.batches.length; i++) { + executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) { + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if (numberOfCommandsToExecute === 0) { + // Driver level error + if (err) return handleCallback(callback, err); + + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + return handleCallback(callback, null, writeResult); + } + }); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeUnorderedBulkOp(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/node_modules/mongodb/lib/change_stream.js b/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 0000000..1d2bbe6 --- /dev/null +++ b/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,455 @@ +'use strict'; + +const EventEmitter = require('events'); +const isResumableError = require('./error').isResumableError; +const MongoError = require('mongodb-core').MongoError; + +var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference']; + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @class ChangeStream + * @since 3.0.0 + * @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream + * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @fires ChangeStream#close + * @fires ChangeStream#change + * @fires ChangeStream#end + * @fires ChangeStream#error + * @return {ChangeStream} a ChangeStream instance. + */ + +class ChangeStream extends EventEmitter { + constructor(changeDomain, pipeline, options) { + super(); + const Collection = require('./collection'); + const Db = require('./db'); + const MongoClient = require('./mongo_client'); + + this.pipeline = pipeline || []; + this.options = options || {}; + this.cursorNamespace = undefined; + this.namespace = {}; + + if (changeDomain instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + this.topology = changeDomain.s.db.serverConfig; + + this.namespace = { + collection: changeDomain.collectionName, + database: changeDomain.s.db.databaseName + }; + + this.cursorNamespace = `${this.namespace.database}.${this.namespace.collection}`; + } else if (changeDomain instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + this.namespace = { collection: '', database: changeDomain.databaseName }; + this.cursorNamespace = this.namespace.database; + this.topology = changeDomain.serverConfig; + } else if (changeDomain instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + this.namespace = { collection: '', database: 'admin' }; + this.cursorNamespace = this.namespace.database; + this.topology = changeDomain.topology; + } else { + throw new TypeError( + 'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' + ); + } + + this.promiseLibrary = changeDomain.s.promiseLibrary; + if (!this.options.readPreference && changeDomain.s.readPreference) { + this.options.readPreference = changeDomain.s.readPreference; + } + + // We need to get the operationTime as early as possible + const isMaster = this.topology.lastIsMaster(); + if (!isMaster) { + throw new MongoError('Topology does not have an ismaster yet.'); + } + + this.operationTime = isMaster.operationTime; + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this); + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this.cursor.on('data', change => + processNewChange({ changeStream: this, change, eventEmitter: true }) + ); + } + }); + + // Listen for all `change` listeners being removed from ChangeStream + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this.cursor.removeAllListeners('data'); + } + }); + } + + /** + * Check if there is any document still available in the Change Stream + * @function ChangeStream.prototype.hasNext + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + return this.cursor.hasNext(callback); + } + + /** + * Get the next available document from the Change Stream, returns null if no more documents are available. + * @function ChangeStream.prototype.next + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + var self = this; + if (this.isClosed()) { + if (callback) return callback(new Error('Change Stream is not open.'), null); + return self.promiseLibrary.reject(new Error('Change Stream is not open.')); + } + + return this.cursor + .next() + .then(change => processNewChange({ changeStream: self, change, callback })) + .catch(error => processNewChange({ changeStream: self, error, callback })); + } + + /** + * Is the cursor closed + * @method ChangeStream.prototype.isClosed + * @return {boolean} + */ + isClosed() { + if (this.cursor) { + return this.cursor.isClosed(); + } + return true; + } + + /** + * Close the Change Stream + * @method ChangeStream.prototype.close + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(callback) { + if (!this.cursor) { + if (callback) return callback(); + return this.promiseLibrary.resolve(); + } + + // Tidy up the existing cursor + var cursor = this.cursor; + delete this.cursor; + return cursor.close(callback); + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @method + * @param {Writable} destination The destination for writing data + * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} + * @return {null} + */ + pipe(destination, options) { + if (!this.pipeDestinations) { + this.pipeDestinations = []; + } + this.pipeDestinations.push(destination); + return this.cursor.pipe(destination, options); + } + + /** + * This method will remove the hooks set up for a previous pipe() call. + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + unpipe(destination) { + if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { + this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); + } + return this.cursor.unpipe(destination); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ + stream(options) { + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** + * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @return {null} + */ + pause() { + return this.cursor.pause(); + } + + /** + * This method will cause the readable stream to resume emitting data events. + * @return {null} + */ + resume() { + return this.cursor.resume(); + } +} + +// Create a new change stream cursor based on self's configuration +var createChangeStreamCursor = function(self) { + if (self.resumeToken) { + self.options.resumeAfter = self.resumeToken; + } + + var changeStreamCursor = buildChangeStreamAggregationCommand(self); + + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * + * @event ChangeStream#change + * @type {object} + */ + if (self.listenerCount('change') > 0) { + changeStreamCursor.on('data', function(change) { + processNewChange({ changeStream: self, change, eventEmitter: true }); + }); + } + + /** + * Change stream close event + * + * @event ChangeStream#close + * @type {null} + */ + changeStreamCursor.on('close', function() { + self.emit('close'); + }); + + /** + * Change stream end event + * + * @event ChangeStream#end + * @type {null} + */ + changeStreamCursor.on('end', function() { + self.emit('end'); + }); + + /** + * Fired when the stream encounters an error. + * + * @event ChangeStream#error + * @type {Error} + */ + changeStreamCursor.on('error', function(error) { + processNewChange({ changeStream: self, error, eventEmitter: true }); + }); + + if (self.pipeDestinations) { + const cursorStream = changeStreamCursor.stream(self.streamOptions); + for (let pipeDestination in self.pipeDestinations) { + cursorStream.pipe(pipeDestination); + } + } + + return changeStreamCursor; +}; + +function getResumeToken(self) { + return self.resumeToken || self.options.resumeAfter; +} + +function getStartAtOperationTime(self) { + const isMaster = self.topology.lastIsMaster() || {}; + return ( + isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime + ); +} + +var buildChangeStreamAggregationCommand = function(self) { + const topology = self.topology; + const namespace = self.namespace; + const pipeline = self.pipeline; + const options = self.options; + const cursorNamespace = self.cursorNamespace; + + var changeStreamStageOptions = { + fullDocument: options.fullDocument || 'default' + }; + + const resumeToken = getResumeToken(self); + const startAtOperationTime = getStartAtOperationTime(self); + if (resumeToken) { + changeStreamStageOptions.resumeAfter = resumeToken; + } + + if (startAtOperationTime) { + changeStreamStageOptions.startAtOperationTime = startAtOperationTime; + } + + // Map cursor options + var cursorOptions = {}; + cursorOptionNames.forEach(function(optionName) { + if (options[optionName]) { + cursorOptions[optionName] = options[optionName]; + } + }); + + if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }]; + + changeStreamPipeline = changeStreamPipeline.concat(pipeline); + + var command = { + aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1, + pipeline: changeStreamPipeline, + readConcern: { level: 'majority' }, + cursor: { + batchSize: options.batchSize || 1 + } + }; + + // Create and return the cursor + return topology.cursor(cursorNamespace, command, cursorOptions); +}; + +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) options.start = process.hrtime(); + const start = options.start || process.hrtime(); + const timeout = options.timeout || SELECTION_TIMEOUT; + const readPreference = options.readPreference; + + if (topology.isConnected({ readPreference })) return callback(null, null); + const hrElapsed = process.hrtime(start); + const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; + if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); + waitForTopologyConnected(topology, options, callback); + }, 3000); // this is an arbitrary wait time to allow SDAM to transition +} + +// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. +function processNewChange(args) { + const changeStream = args.changeStream; + const error = args.error; + const change = args.change; + const callback = args.callback; + const eventEmitter = args.eventEmitter || false; + const topology = changeStream.topology; + const options = changeStream.cursor.options; + + if (error) { + if (isResumableError(error) && !changeStream.attemptingResume) { + changeStream.attemptingResume = true; + + if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) { + const startAtOperationTime = changeStream.cursor.cursorState.operationTime; + changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options); + } + + // stop listening to all events from old cursor + ['data', 'close', 'end', 'error'].forEach(event => + changeStream.cursor.removeAllListeners(event) + ); + + // close internal cursor, ignore errors + changeStream.cursor.close(); + + // attempt recreating the cursor + if (eventEmitter) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return changeStream.emit('error', err); + changeStream.cursor = createChangeStreamCursor(changeStream); + }); + + return; + } + + if (callback) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return callback(err, null); + + changeStream.cursor = createChangeStreamCursor(changeStream); + changeStream.next(callback); + }); + + return; + } + + return new Promise((resolve, reject) => { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return reject(err); + resolve(); + }); + }) + .then(() => (changeStream.cursor = createChangeStreamCursor(changeStream))) + .then(() => changeStream.next()); + } + + if (eventEmitter) return changeStream.emit('error', error); + if (typeof callback === 'function') return callback(error, null); + return changeStream.promiseLibrary.reject(error); + } + + changeStream.attemptingResume = false; + + // Cache the resume token if it is present. If it is not present return an error. + if (!change || !change._id) { + var noResumeTokenError = new Error( + 'A change stream document has been received that lacks a resume token (_id).' + ); + + if (eventEmitter) return changeStream.emit('error', noResumeTokenError); + if (typeof callback === 'function') return callback(noResumeTokenError, null); + return changeStream.promiseLibrary.reject(noResumeTokenError); + } + + changeStream.resumeToken = change._id; + + // Return the change + if (eventEmitter) return changeStream.emit('change', change); + if (typeof callback === 'function') return callback(error, change); + return changeStream.promiseLibrary.resolve(change); +} + +/** + * The callback format for results + * @callback ChangeStream~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +module.exports = ChangeStream; diff --git a/node_modules/mongodb/lib/collection.js b/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..081f970 --- /dev/null +++ b/node_modules/mongodb/lib/collection.js @@ -0,0 +1,2087 @@ +'use strict'; + +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const checkCollectionName = require('./utils').checkCollectionName; +const ObjectID = require('mongodb-core').BSON.ObjectID; +const AggregationCursor = require('./aggregation_cursor'); +const MongoError = require('mongodb-core').MongoError; +const toError = require('./utils').toError; +const normalizeHintField = require('./utils').normalizeHintField; +const handleCallback = require('./utils').handleCallback; +const decorateCommand = require('./utils').decorateCommand; +const decorateWithCollation = require('./utils').decorateWithCollation; +const decorateWithReadConcern = require('./utils').decorateWithReadConcern; +const formattedOrderClause = require('./utils').formattedOrderClause; +const ReadPreference = require('mongodb-core').ReadPreference; +const CommandCursor = require('./command_cursor'); +const unordered = require('./bulk/unordered'); +const ordered = require('./bulk/ordered'); +const ChangeStream = require('./change_stream'); +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; +const resolveReadPreference = require('./utils').resolveReadPreference; + +// Operations +const bulkWrite = require('./operations/collection_ops').bulkWrite; +const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; +const count = require('./operations/collection_ops').count; +const countDocuments = require('./operations/collection_ops').countDocuments; +const createIndex = require('./operations/collection_ops').createIndex; +const createIndexes = require('./operations/collection_ops').createIndexes; +const deleteMany = require('./operations/collection_ops').deleteMany; +const deleteOne = require('./operations/collection_ops').deleteOne; +const distinct = require('./operations/collection_ops').distinct; +const dropIndex = require('./operations/collection_ops').dropIndex; +const dropIndexes = require('./operations/collection_ops').dropIndexes; +const ensureIndex = require('./operations/collection_ops').ensureIndex; +const findAndModify = require('./operations/collection_ops').findAndModify; +const findAndRemove = require('./operations/collection_ops').findAndRemove; +const findOne = require('./operations/collection_ops').findOne; +const findOneAndDelete = require('./operations/collection_ops').findOneAndDelete; +const findOneAndReplace = require('./operations/collection_ops').findOneAndReplace; +const findOneAndUpdate = require('./operations/collection_ops').findOneAndUpdate; +const geoHaystackSearch = require('./operations/collection_ops').geoHaystackSearch; +const group = require('./operations/collection_ops').group; +const indexes = require('./operations/collection_ops').indexes; +const indexExists = require('./operations/collection_ops').indexExists; +const indexInformation = require('./operations/collection_ops').indexInformation; +const insertOne = require('./operations/collection_ops').insertOne; +const isCapped = require('./operations/collection_ops').isCapped; +const mapReduce = require('./operations/collection_ops').mapReduce; +const optionsOp = require('./operations/collection_ops').optionsOp; +const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; +const prepareDocs = require('./operations/collection_ops').prepareDocs; +const reIndex = require('./operations/collection_ops').reIndex; +const removeDocuments = require('./operations/collection_ops').removeDocuments; +const rename = require('./operations/collection_ops').rename; +const replaceOne = require('./operations/collection_ops').replaceOne; +const save = require('./operations/collection_ops').save; +const stats = require('./operations/collection_ops').stats; +const updateDocuments = require('./operations/collection_ops').updateDocuments; +const updateMany = require('./operations/collection_ops').updateMany; +const updateOne = require('./operations/collection_ops').updateOne; + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + */ + +const mergeKeys = ['ignoreUndefined']; + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +function Collection(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + const internalHint = null; + const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + const serializeFunctions = + options == null || options.serializeFunctions == null + ? db.s.options.serializeFunctions + : options.serializeFunctions; + const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + const promoteLongs = + options == null || options.promoteLongs == null + ? db.s.options.promoteLongs + : options.promoteLongs; + const promoteValues = + options == null || options.promoteValues == null + ? db.s.options.promoteValues + : options.promoteValues; + const promoteBuffers = + options == null || options.promoteBuffers == null + ? db.s.options.promoteBuffers + : options.promoteBuffers; + let readPreference = null; + const collectionHint = null; + const namespace = `${dbName}.${name}`; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Assign the right collection level readPreference + if (options && options.readPreference) { + readPreference = options.readPreference; + } else if (db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null ? ObjectID : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory, + // Db + db: db, + // Topology + topology: topology, + // dbName + dbName: dbName, + // Options + options: options, + // Namespace + namespace: namespace, + // Read preference + readPreference: readPreference, + // SlaveOK + slaveOk: slaveOk, + // Serialize functions + serializeFunctions: serializeFunctions, + // Raw + raw: raw, + // promoteLongs + promoteLongs: promoteLongs, + // promoteValues + promoteValues: promoteValues, + // promoteBuffers + promoteBuffers: promoteBuffers, + // internalHint + internalHint: internalHint, + // collectionHint + collectionHint: collectionHint, + // Name + name: name, + // Promise library + promiseLibrary: promiseLibrary, + // Read Concern + readConcern: options.readConcern, + // Write Concern + writeConcern: options.writeConcern + }; +} + +Object.defineProperty(Collection.prototype, 'dbName', { + enumerable: true, + get: function() { + return this.s.dbName; + } +}); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, + get: function() { + return this.s.name; + } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace; + } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, + get: function() { + return this.s.readConcern || { level: 'local' }; + } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable: true, + get: function() { + let ops = {}; + if (this.s.writeConcern) { + return this.s.writeConcern; + } + + if (this.s.options.w != null) ops.w = this.s.options.w; + if (this.s.options.j != null) ops.j = this.s.options.j; + if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, 'hint', { + enumerable: true, + get: function() { + return this.s.collectionHint; + }, + set: function(v) { + this.s.collectionHint = normalizeHintField(v); + } +}); + +const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} [query={}] The cursor query object. + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `find()` must be a callback or undefined'); + } + + let selector = query; + // figuring out arguments + if (typeof callback !== 'function') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } else if (options == null) { + callback = typeof selector === 'function' ? selector : undefined; + selector = typeof selector === 'object' ? selector : undefined; + } + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + const object = selector; + if (Buffer.isBuffer(object)) { + const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); + if (object_size !== object.length) { + const error = new Error( + 'query selector raw message size does not match message header size [' + + object.length + + '] != [' + + object_size + + ']' + ); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if (selector != null && selector._bsontype === 'ObjectID') { + selector = { _id: selector }; + } + + if (!options) options = {}; + + let projection = options.projection || options.fields; + + if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + // Make a shallow copy of options + let newOptions = Object.assign({}, options); + + // Make a shallow copy of the collection options + for (let key in this.s.options) { + if (mergeKeys.indexOf(key) !== -1) { + newOptions[key] = this.s.options[key]; + } + } + + // Unpack options + newOptions.skip = options.skip ? options.skip : 0; + newOptions.limit = options.limit ? options.limit : 0; + newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = + options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions.readPreference = resolveReadPreference(newOptions, { + db: this.s.db, + collection: this + }); + + // Set slave ok to true if read preference different from primary + if ( + newOptions.readPreference != null && + (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') + ) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if (selector != null && typeof selector !== 'object') { + throw MongoError.create({ message: 'query selector must be an object', driver: true }); + } + + // Build the find command + const findCommand = { + find: this.s.namespace, + limit: newOptions.limit, + skip: newOptions.skip, + query: selector + }; + + // Ensure we use the right await data option + if (typeof newOptions.awaitdata === 'boolean') { + newOptions.awaitData = newOptions.awaitdata; + } + + // Translate to new command option noCursorTimeout + if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + decorateCommand(findCommand, newOptions, ['session', 'collation']); + + if (projection) findCommand.fields = projection; + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') + newOptions.promoteLongs = this.s.promoteLongs; + if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') + newOptions.promoteValues = this.s.promoteValues; + if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') + newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if (findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + decorateWithReadConcern(findCommand, this, options); + + // Decorate find command with collation options + try { + decorateWithCollation(findCommand, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + const cursor = this.s.topology.cursor(this.s.namespace, findCommand, newOptions); + + return typeof callback === 'function' ? handleCallback(callback, null, cursor) : cursor; + } +); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]); +}; + +function mapInsertManyResults(docs, r) { + const finalResult = { + result: { ok: 1, n: r.insertedCount }, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: r.insertedIds + }; + + if (r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + if (!Array.isArray(docs) && typeof callback === 'function') { + return callback( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + } else if (!Array.isArray(docs)) { + return new this.s.promiseLibrary((resolve, reject) => { + reject( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + }); + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || this.s.serializeFunctions; + + docs = prepareDocs(this, docs, options); + + // Generate the bulk write operations + const operations = [ + { + insertMany: docs + } + ]; + + return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], { + resultMutator: result => mapInsertManyResults(docs, result) + }); +}; + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {BulkWriteError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); + } + + return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]); +}; + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = deprecate(function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + * @property {Object} message + * @property {Array} ops + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document in a collection + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]); +}; + +/** + * Replace a document in a collection with another document + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]); +}; + +/** + * Update multiple documents in a collection + * @method + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]); +}; + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = deprecate(function(selector, document, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, updateDocuments, [ + this, + selector, + document, + options, + callback + ]); +}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document from a collection + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]); +}; + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents from a collection + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]); +}; + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = deprecate(function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, removeDocuments, [this, selector, options, callback]); +}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = deprecate(function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndfined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeOperation(this.s.topology, save, [this, doc, options, callback]); +}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * The callback format for an aggregation call + * @callback Collection~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `findOne()` must be a callback or undefined'); + } + + if (typeof query === 'function') (callback = query), (query = {}), (options = {}); + if (typeof options === 'function') (callback = options), (options = {}); + query = query || {}; + options = options || {}; + + return executeOperation(this.s.topology, findOne, [this, query, options, callback]); + } +); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + return executeOperation(this.s.topology, rename, [this, newName, options, callback]); +}; + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, this.s.db.dropCollection.bind(this.s.db), [ + this.s.name, + options, + callback + ]); +}; + +/** + * Returns the options of the collection. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(opts, callback) { + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + return executeOperation(this.s.topology, optionsOp, [this, opts, callback]); +}; + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, isCapped, [this, options, callback]); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, createIndex, [this, fieldOrSpec, options, callback]); +}; + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation(this.s.topology, createIndexes, [this, indexSpecs, options, callback]); +}; + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation(this.s.topology, dropIndex, [this, indexName, options, callback]); +}; + +/** + * Drops all indexes from this collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + return executeOperation(this.s.topology, dropIndexes, [this, options, callback]); +}; + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = deprecate( + Collection.prototype.dropIndexes, + 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' +); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, reIndex, [this, options, callback]); +}; + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = Object.assign({}, options); + // Determine the read preference in the options. + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // Cursor options + let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; + + // We have a list collections command + if (this.s.topology.capabilities().hasListIndexesCommand) { + // Build the command + const command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + cursor = this.s.topology.cursor(`${this.s.dbName}.$cmd`, command, options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Return the cursor + return cursor; + } + + // Get the namespace + const ns = `${this.s.dbName}.system.indexes`; + // Get the query + cursor = this.s.topology.cursor(ns, { find: ns, query: { ns: this.s.namespace } }, options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if (options.batchSize) cursor = cursor.batchSize(options.batchSize); + // Return the cursor + return cursor; +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, ensureIndex, [this, fieldOrSpec, options, callback]); +}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexExists, [this, indexes, options, callback]); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, indexInformation, [this, options, callback]); +}; + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} [query={}] The query for the count. + * @param {object} [options] Optional settings. + * @param {boolean} [options.limit] The limit of documents to count. + * @param {boolean} [options.skip] The number of documents to skip for the count. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead + */ +Collection.prototype.count = deprecate(function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, count, [this, query, options, callback]); +}, 'collection.count is deprecated, and will be removed in a future version.' + + ' Use collection.countDocuments or collection.estimatedDocumentCount instead'); + +/** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + */ +Collection.prototype.estimatedDocumentCount = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, count, [this, null, options, callback]); +}; + +/** + * Gets the number of documents matching the filter. + * + * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param {object} [query] the query for the count + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specifies a collation. + * @param {string|object} [options.hint] The index to use. + * @param {number} [options.limit] The maximum number of document to count. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {number} [options.skip] The number of documents to skip before counting. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + +Collection.prototype.countDocuments = function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, countDocuments, [this, query, options, callback]); +}; + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + const queryOption = args.length ? args.shift() || {} : {}; + const optionsOption = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, distinct, [ + this, + key, + queryOption, + optionsOption, + callback + ]); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexes, [this, options, callback]); +}; + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, stats, [this, options, callback]); +}; + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + + return executeOperation(this.s.topology, findOneAndDelete, [this, filter, options, callback]); +}; + +/** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} replacement The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (replacement == null || typeof replacement !== 'object') + throw toError('replacement parameter must be an object'); + + return executeOperation(this.s.topology, findOneAndReplace, [ + this, + filter, + replacement, + options, + callback + ]); +}; + +/** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (update == null || typeof update !== 'object') + throw toError('update parameter must be an object'); + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + return executeOperation(this.s.topology, findOneAndUpdate, [ + this, + filter, + update, + options, + callback + ]); +}; + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = deprecate(function(query, sort, doc, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = Object.assign({}, options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation(this.s.topology, findAndModify, [ + this, + query, + sort, + doc, + options, + callback + ]); +}, 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.'); + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, findAndRemove, [this, query, sort, options, callback]); +}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if (Array.isArray(pipeline)) { + // Set up callback if one is provided + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + const args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + const opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = + opts && + (opts.readPreference || + opts.explain || + opts.cursor || + opts.out || + opts.maxTimeMS || + opts.hint || + opts.allowDiskUse) + ? args.pop() + : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // Ignore readConcern option + let ignoreReadConcern = false; + + // Build the command + const command = { aggregate: this.s.name, pipeline: pipeline }; + + // If out was specified + if (typeof options.out === 'string') { + pipeline.push({ $out: options.out }); + // Ignore read concern + ignoreReadConcern = true; + } else if (pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) { + ignoreReadConcern = true; + } + + // Decorate command with writeConcern if out has been specified + if ( + pipeline.length > 0 && + pipeline[pipeline.length - 1]['$out'] && + this.s.topology.capabilities().commandsTakeWriteConcern + ) { + applyWriteConcern(command, { db: this.s.db, collection: this }, options); + } + + // Have we specified collation + try { + decorateWithCollation(command, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + // If we have bypassDocumentValidation set + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if (!ignoreReadConcern) { + decorateWithReadConcern(command, this, options); + } + + // If we have allowDiskUse defined + if (options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; + + // If we are giving a hint + if (options.hint) command.hint = options.hint; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + + // If explain has been specified add it + if (options.explain) { + if (command.readConcern || command.writeConcern) { + throw toError('"explain" cannot be used on an aggregate call with readConcern/writeConcern'); + } + command.explain = options.explain; + } + + if (typeof options.comment === 'string') command.comment = options.comment; + + // Validate that cursor options is valid + if (options.cursor != null && typeof options.cursor !== 'object') { + throw toError('cursor options must be an object'); + } + + options.cursor = options.cursor || {}; + if (options.batchSize) options.cursor.batchSize = options.batchSize; + command.cursor = options.cursor; + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if (typeof callback !== 'function') { + if (!this.s.topology.capabilities()) { + throw new MongoError('cannot connect to server'); + } + + // Allow disk usage command + if (typeof options.allowDiskUse === 'boolean') command.allowDiskUse = options.allowDiskUse; + if (typeof options.maxTimeMS === 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, command, options)); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * @method + * @since 3.0.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Collection.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: this.s.db, collection: this }); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (options.session) { + options.session = undefined; + } + + return executeOperation(this.s.topology, parallelCollectionScan, [this, options, callback], { + skipSessions: true + }); +}; + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance] Include results up to maxDistance from the point. + * @param {object} [options.search] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, geoHaystackSearch, [this, x, y, options, callback]); +}; + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. + */ +Collection.prototype.group = deprecate(function( + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback +) { + const args = Array.prototype.slice.call(arguments, 3); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if (!(typeof finalize === 'function')) { + command = finalize; + finalize = null; + } + + if ( + !Array.isArray(keys) && + keys instanceof Object && + typeof keys !== 'function' && + !(keys._bsontype === 'Code') + ) { + keys = Object.keys(keys); + } + + if (typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if (typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + return executeOperation(this.s.topology, group, [ + this, + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback + ]); +}, +'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query] Query filter object. + * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize] Finalize function. + * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if (null == options.out) { + throw new Error( + 'the out option parameter must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + return executeOperation(this.s.topology, mapReduce, [this, map, reduce, options, callback]); +}; + +/** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +}; + +/** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Collection.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +module.exports = Collection; diff --git a/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..50afb6f --- /dev/null +++ b/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,334 @@ +'use strict'; + +const inherits = require('util').inherits; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('./cursor'); + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology Options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Optional ClientSession + session: options.session + }; +}; + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = [ + '_next', + 'next', + 'hasNext', + 'each', + 'forEach', + 'toArray', + 'rewind', + 'bufferedCount', + 'readBufferedDocuments', + 'close', + 'isClosed', + 'kill', + 'setCursorBatchSize', + '_find', + '_getmore', + '_killcursor', + 'isDead', + 'explain', + 'isNotified', + 'isKilled', + '_endSession', + '_initImplicitSession' +]; + +// Only inherit the types we need +for (var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +CommandCursor.prototype.setReadPreference = function(readPreference) { + if (this.s.state === CommandCursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (this.s.state !== CommandCursor.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.s.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.s.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; +}; + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if (this.s.state === CommandCursor.CLOSED || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + if (typeof value !== 'number') + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + if (this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if (this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +CommandCursor.prototype.getLogger = function() { + return this.logger; +}; + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function CommandCursor.prototype.hasNext + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * 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. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/node_modules/mongodb/lib/constants.js b/node_modules/mongodb/lib/constants.js new file mode 100644 index 0000000..d6cc68a --- /dev/null +++ b/node_modules/mongodb/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', + SYSTEM_INDEX_COLLECTION: 'system.indexes', + SYSTEM_PROFILE_COLLECTION: 'system.profile', + SYSTEM_USER_COLLECTION: 'system.users', + SYSTEM_COMMAND_COLLECTION: '$cmd', + SYSTEM_JS_COLLECTION: 'system.js' +}; diff --git a/node_modules/mongodb/lib/cursor.js b/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..4a0b815 --- /dev/null +++ b/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1152 @@ +'use strict'; + +const Transform = require('stream').Transform; +const PassThrough = require('stream').PassThrough; +const inherits = require('util').inherits; +const deprecate = require('util').deprecate; +const handleCallback = require('./utils').handleCallback; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const Readable = require('stream').Readable; +const CoreCursor = require('mongodb-core').Cursor; +const Map = require('mongodb-core').BSON.Map; +const executeOperation = require('./utils').executeOperation; + +const count = require('./operations/cursor_ops').count; +const each = require('./operations/cursor_ops').each; +const hasNext = require('./operations/cursor_ops').hasNext; +const next = require('./operations/cursor_ops').next; +const toArray = require('./operations/cursor_ops').toArray; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +const fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor max + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(true) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +function Cursor(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + const state = Cursor.INIT; + const streamOptions = {}; + + // Tailable cursor options + const numberOfRetries = options.numberOfRetries || 5; + const tailableRetryInterval = options.tailableRetryInterval || 500; + const currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Set up + Readable.call(this, { objectMode: true }); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries, + tailableRetryInterval: tailableRetryInterval, + currentNumberOfRetries: currentNumberOfRetries, + // State + state: state, + // Stream options + streamOptions: streamOptions, + // BSON + bson: bson, + // Namespace + ns: ns, + // Command + cmd: cmd, + // Options + options: options, + // Topology + topology: topology, + // Topology options + topologyOptions: topologyOptions, + // Promise library + promiseLibrary: promiseLibrary, + // Current doc + currentDoc: null, + // explicitlyIgnoreSession + explicitlyIgnoreSession: options.explicitlyIgnoreSession + }; + + // Optional ClientSession + if (!options.explicitlyIgnoreSession && options.session) { + this.s.session = options.session; + } + + // Translate correctly + if (this.s.options.noCursorTimeout === true) { + this.addCursorFlag('noCursorTimeout', true); + } + + // Set the sort value + this.sortValue = this.s.cmd.sort; + + // Get the batchSize + const batchSize = + cmd.cursor && cmd.cursor.batchSize + ? cmd.cursor && cmd.cursor.batchSize + : options.cursor && options.cursor.batchSize + ? options.cursor.batchSize + : 1000; + + // Set the batchSize + this.setCursorBatchSize(batchSize); +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +Cursor.prototype._next = function() { + if (this._initImplicitSession) { + this._initImplicitSession(); + } + return CoreCursor.prototype.next.apply(this, arguments); +}; + +for (let name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +Cursor.prototype._initImplicitSession = function() { + if (!this.s.explicitlyIgnoreSession && !this.s.session && this.s.topology.hasSessionSupport()) { + this.s.session = this.s.topology.startSession({ owner: this }); + this.cursorState.session = this.s.session; + } +}; + +Cursor.prototype._endSession = function() { + const didCloseCursor = CoreCursor.prototype._endSession.apply(this, arguments); + if (didCloseCursor) { + this.s.session = undefined; + } +}; + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + return executeOperation(this.s.topology, hasNext, [this, callback], { + skipSessions: true + }); +}; + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + return executeOperation(this.s.topology, next, [this, callback], { + skipSessions: true + }); +}; + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.query = filter; + return this; +}; + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ +Cursor.prototype.maxScan = deprecate(function(maxScan) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxScan = maxScan; + return this; +}, 'Cursor.maxScan is deprecated, and will be removed in a later version'); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.hint = hint; + return this; +}; + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + this.s.cmd.min = min; + return this; +}; + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.max = max; + return this; +}; + +/** + * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * @method + * @param {bool} returnKey the returnKey value. + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.returnKey = value; + return this; +}; + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.showDiskLoc = value; + return this; +}; + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ +Cursor.prototype.snapshot = deprecate(function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.snapshot = value; + return this; +}, 'Cursor Snapshot is deprecated, and will be removed in a later version'); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (fields.indexOf(field) === -1) { + throw MongoError.create({ + message: `option ${field} is not a supported option ${fields}`, + driver: true + }); + } + + this.s[field] = value; + if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; + return this; +}; + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (flags.indexOf(flag) === -1) { + throw MongoError.create({ + message: `flag ${flag} is not a supported flag ${flags}`, + driver: true + }); + } + + if (typeof value !== 'boolean') { + throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); + } + + this.s.cmd[flag] = value; + return this; +}; + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {string|boolean|number} value The modifier value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (name[0] !== '$') { + throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); + } + + // Strip of the $ + const field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if (field === 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +}; + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.comment = value; + return this; +}; + +/** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxAwaitTimeMS = function(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxAwaitTimeMS = value; + return this; +}; + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.maxTimeMS = value; + return this; +}; + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.s.cmd.fields = value; + return this; +}; + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.s.state === Cursor.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + let order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if (Array.isArray(order) && Array.isArray(order[0])) { + order = new Map( + order.map(x => { + const value = [x[0], null]; + if (x[1] === 'asc') { + value[1] = 1; + } else if (x[1] === 'desc') { + value[1] = -1; + } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { + value[1] = x[1]; + } else { + throw new MongoError( + "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return value; + }) + ); + } + + if (direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +}; + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support batchSize", driver: true }); + } + + if (this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +}; + +/** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.collation = function(value) { + this.s.cmd.collation = value; + return this; +}; + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); + } + + if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'limit requires an integer', driver: true }); + } + + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +}; + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if (this.s.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); + } + + if (this.s.state === Cursor.OPEN || this.s.state === Cursor.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'skip requires an integer', driver: true }); + } + + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +}; + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * 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. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = deprecate(function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + each(this, callback); +}, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {Promise} if no callback supplied + */ +Cursor.prototype.forEach = function(iterator, callback) { + // Rewind cursor state + this.rewind(); + + // Set current cursor to INIT + this.s.state = Cursor.INIT; + + if (typeof callback === 'function') { + each(this, (err, doc) => { + if (err) { + callback(err); + return false; + } + if (doc != null) { + iterator(doc); + return true; + } + if (doc == null && callback) { + const internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); + } else { + return new this.s.promiseLibrary((fulfill, reject) => { + each(this, (err, doc) => { + if (err) { + reject(err); + return false; + } else if (doc == null) { + fulfill(null); + return false; + } else { + iterator(doc); + return true; + } + }); + }); + } +}; + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(readPreference) { + if (this.s.state !== Cursor.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.s.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.s.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; +}; + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * 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 contains partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + if (this.s.options.tailable) { + throw MongoError.create({ + message: 'Tailable cursor cannot be converted to array', + driver: true + }); + } + + return executeOperation(this.s.topology, toArray, [this, callback], { + skipSessions: true + }); +}; + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options] Optional settings. + * @param {number} [options.skip] The number of documents to skip. + * @param {number} [options.limit] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + if (this.s.cmd.query == null) + throw MongoError.create({ message: 'count can only be used with find command', driver: true }); + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + if (typeof applySkipLimit === 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if (this.s.session) { + opts = Object.assign({}, opts, { session: this.s.session }); + } + + return executeOperation(this.s.topology, count, [this, applySkipLimit, opts, callback], { + skipSessions: !!this.s.session + }); +}; + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { skipKillCursors: false }, options); + + this.s.state = Cursor.CLOSED; + if (!options.skipKillCursors) { + // Kill the cursor + this.kill(); + } + + const completeClose = () => { + // Emit the close event for the cursor + this.emit('close'); + + // Callback if provided + if (typeof callback === 'function') { + return handleCallback(callback, null, this); + } + + // Return a Promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); + }; + + if (this.s.session) { + if (typeof callback === 'function') { + return this._endSession(() => completeClose()); + } + + return new this.s.promiseLibrary(resolve => { + this._endSession(() => completeClose().then(resolve)); + }); + } + + return completeClose(); +}; + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ +Cursor.prototype.map = function(transform) { + if (this.cursorState.transforms && this.cursorState.transforms.doc) { + const oldTransform = this.cursorState.transforms.doc; + this.cursorState.transforms.doc = doc => { + return transform(oldTransform(doc)); + }; + } else { + this.cursorState.transforms = { doc: transform }; + } + return this; +}; + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +}; + +Cursor.prototype.destroy = function(err) { + if (err) this.emit('error', err); + this.pause(); + this.close(); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + * TODO: replace this method with transformStream in next major release + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +}; + +/** + * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, + * returns a stream of unmodified docs. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {stream} + */ +Cursor.prototype.transformStream = function(options) { + const streamOptions = options || {}; + if (typeof streamOptions.transform === 'function') { + const stream = new Transform({ + objectMode: true, + transform: function(chunk, encoding, callback) { + this.push(streamOptions.transform(chunk)); + callback(); + } + }); + + return this.pipe(stream); + } + return this.pipe(new PassThrough({ objectMode: true })); +}; + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + this.s.cmd.explain = true; + + // Do we have a readConcern + if (this.s.cmd.readConcern) { + delete this.s.cmd['readConcern']; + } + + return executeOperation(this.s.topology, this._next.bind(this), [callback], { + skipSessions: true + }); +}; + +Cursor.prototype._read = function() { + if (this.s.state === Cursor.CLOSED || this.isDead()) { + return this.push(null); + } + + // Get the next item + this.next((err, result) => { + if (err) { + if (this.listeners('error') && this.listeners('error').length > 0) { + this.emit('error', err); + } + if (!this.isDead()) this.close(); + + // Emit end event + this.emit('end'); + return this.emit('finish'); + } + + // If we provided a transformation method + if (typeof this.s.streamOptions.transform === 'function' && result != null) { + return this.push(this.s.streamOptions.transform(result)); + } + + // If we provided a map function + if ( + this.cursorState.transforms && + typeof this.cursorState.transforms.doc === 'function' && + result != null + ) { + return this.push(this.cursorState.transforms.doc(result)); + } + + // Return the result + this.push(result); + + if (result === null && this.isDead()) { + this.once('end', () => { + this.close(); + this.emit('finish'); + }); + } + }); +}; + +/** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ +Cursor.prototype.getLogger = function() { + return this.logger; +}; + +Object.defineProperty(Cursor.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + return this.s.options.readPreference; + } +}); + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + const ns = this.s.ns || ''; + const firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/node_modules/mongodb/lib/db.js b/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..b3257f3 --- /dev/null +++ b/node_modules/mongodb/lib/db.js @@ -0,0 +1,985 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const inherits = require('util').inherits; +const getSingleProperty = require('./utils').getSingleProperty; +const CommandCursor = require('./command_cursor'); +const handleCallback = require('./utils').handleCallback; +const filterOptions = require('./utils').filterOptions; +const toError = require('./utils').toError; +const ReadPreference = require('mongodb-core').ReadPreference; +const MongoError = require('mongodb-core').MongoError; +const ObjectID = require('mongodb-core').ObjectID; +const Logger = require('mongodb-core').Logger; +const Collection = require('./collection'); +const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; +const executeOperation = require('./utils').executeOperation; +const applyWriteConcern = require('./utils').applyWriteConcern; +const resolveReadPreference = require('./utils').resolveReadPreference; +const ChangeStream = require('./change_stream'); +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const CONSTANTS = require('./constants'); + +// Operations +const addUser = require('./operations/db_ops').addUser; +const collections = require('./operations/db_ops').collections; +const createCollection = require('./operations/db_ops').createCollection; +const createIndex = require('./operations/db_ops').createIndex; +const createListener = require('./operations/db_ops').createListener; +const dropCollection = require('./operations/db_ops').dropCollection; +const dropDatabase = require('./operations/db_ops').dropDatabase; +const ensureIndex = require('./operations/db_ops').ensureIndex; +const evaluate = require('./operations/db_ops').evaluate; +const executeCommand = require('./operations/db_ops').executeCommand; +const executeDbAdminCommand = require('./operations/db_ops').executeDbAdminCommand; +const indexInformation = require('./operations/db_ops').indexInformation; +const listCollectionsTransforms = require('./operations/db_ops').listCollectionsTransforms; +const profilingInfo = require('./operations/db_ops').profilingInfo; +const profilingLevel = require('./operations/db_ops').profilingLevel; +const removeUser = require('./operations/db_ops').removeUser; +const setProfilingLevel = require('./operations/db_ops').setProfilingLevel; +const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + */ + +// Allowed parameters +const legalOptionNames = [ + 'w', + 'wtimeout', + 'fsync', + 'j', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'bufferMaxEntries', + 'authSource', + 'ignoreUndefined', + 'promoteLongs', + 'promiseLibrary', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'parentDb', + 'noListener', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options] Optional settings. + * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +function Db(databaseName, topology, options) { + options = options || {}; + if (!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName, + // DbCache + dbCache: {}, + // Children db's + children: [], + // Topology + topology: topology, + // Options + options: options, + // Logger instance + logger: Logger('Db', options), + // Get the bson parser + bson: topology ? topology.bson : null, + // Unpack read preference + readPreference: options.readPreference, + // Set buffermaxEntries + bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, + // Parent db (if chained) + parentDb: options.parentDb || null, + // Set up the primary key factory or fallback to ObjectID + pkFactory: options.pkFactory || ObjectID, + // Get native parser + nativeParser: options.nativeParser || options.native_parser, + // Promise library + promiseLibrary: promiseLibrary, + // No listener + noListener: typeof options.noListener === 'boolean' ? options.noListener : false, + // ReadConcern + readConcern: options.readConcern + }; + + // Ensure we have a valid db name + validateDatabaseName(this.s.databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', this.s.topology); + getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', this.s.databaseName); + + // This is a child db, do not register any listeners + if (options.parentDb) return; + if (this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(this, 'error', this)); + topology.on('timeout', createListener(this, 'timeout', this)); + topology.on('close', createListener(this, 'close', this)); + topology.on('parseError', createListener(this, 'parseError', this)); + topology.once('open', createListener(this, 'open', this)); + topology.once('fullsetup', createListener(this, 'fullsetup', this)); + topology.once('all', createListener(this, 'all', this)); + topology.on('reconnect', createListener(this, 'reconnect', this)); +} + +inherits(Db, EventEmitter); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable: true, + get: function() { + return this.s.topology; + } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable: true, + get: function() { + return this.s.options; + } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable: true, + get: function() { + if ( + this.s.options.readPreference != null && + (this.s.options.readPreference !== 'primary' || + this.s.options.readPreference.mode !== 'primary') + ) { + return true; + } + return false; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable: true, + get: function() { + const ops = {}; + if (this.s.options.w != null) ops.w = this.s.options.w; + if (this.s.options.j != null) ops.j = this.s.options.j; + if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]); +}; + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + const Admin = require('./admin'); + + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +const collectionKeys = [ + 'pkFactory', + 'readPreference', + 'serializeFunctions', + 'strict', + 'readConcern', + 'ignoreUndefined', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs' +]; + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you + * can use it without a callback in the following way: `const collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} [callback] The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options = Object.assign({}, options); + + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if (this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Merge in all needed options and ensure correct writeConcern merging from db level + options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); + + // Execute + if (options == null || !options.strict) { + try { + const collection = new Collection( + this, + this.s.topology, + this.s.databaseName, + name, + this.s.pkFactory, + options + ); + if (callback) callback(null, collection); + return collection; + } catch (err) { + if (err instanceof MongoError && callback) return callback(err); + throw err; + } + } + + // Strict mode + if (typeof callback !== 'function') { + throw toError(`A callback is required in strict mode. While getting collection ${name}`); + } + + // Did the user destroy the topology + if (this.serverConfig && this.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + + // Strict mode + this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length === 0) + return handleCallback( + callback, + toError(`Collection ${name} does not exist. Currently in strict mode.`), + null + ); + + try { + return handleCallback( + callback, + null, + new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err, null); + } + }); +}; + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 + * @param {number} [options.size] The size of the capped collection in bytes. + * @param {number} [options.max] The maximum number of documents in the capped collection. + * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. + * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. + * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. + * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. + * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. + * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. + * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. + * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = deprecateOptions( + { + name: 'Db.createCollection', + deprecatedOptions: ['autoIndexId'], + optionsIndex: 1 + }, + function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + return executeOperation(this.s.topology, createCollection, [this, name, options, callback]); + } +); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Build command object + const commandObject = { dbStats: true }; + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if (options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + // Execute the command + return this.command(commandObject, options, callback); +}; + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} [filter={}] Query to filter collections by + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info + * @param {number} [options.batchSize] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = Object.assign({}, options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // Ensure valid readPreference + options.readPreference = resolveReadPreference(options, { + db: this, + default: ReadPreference.primary + }); + + // Cursor options + let cursor = options.batchSize ? { batchSize: options.batchSize } : {}; + + // We have a list collections command + if (this.serverConfig.capabilities().hasListCollectionsCommand) { + const nameOnly = typeof options.nameOnly === 'boolean' ? options.nameOnly : false; + // Build the command + const command = { listCollections: true, filter, cursor, nameOnly }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Create the cursor + cursor = this.s.topology.cursor(`${this.s.databaseName}.$cmd`, command, options); + // Do we have a readPreference, apply it + if (options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + // Return the cursor + return cursor; + } + + // We cannot use the listCollectionsCommand + if (!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if ( + typeof filter.name === 'string' && + !new RegExp('^' + this.databaseName + '\\.').test(filter.name) + ) { + filter = Object.assign({}, filter); + filter.name = `${this.s.databaseName}.${filter.name}`; + } + } + + // No filter, filter by current database + if (filter == null) { + filter.name = `/${this.s.databaseName}/`; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + // Return options + const _options = { transforms: listCollectionsTransforms(this.s.databaseName) }; + // Get the cursor + cursor = this.collection(CONSTANTS.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options); + // Do we have a readPreference, apply it + if (options.readPreference) cursor.setReadPreference(options.readPreference); + // Set the passed in batch size if one was provided + if (options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = deprecate(function(code, parameters, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]); +}, 'Db.eval is deprecated as of MongoDB version 3.2'); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Add return new collection + options.new_collection = true; + + const collection = this.collection(fromCollection); + return executeOperation(this.s.topology, collection.rename.bind(collection), [ + toCollection, + options, + callback + ]); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Command to execute + const cmd = { drop: name }; + + // Decorate with write concern + applyWriteConcern(cmd, { db: this }, options); + + // options + const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY }); + if (options.session) opts.session = options.session; + + return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]); +}; + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Drop database command + const cmd = { dropDatabase: 1 }; + + // Decorate with write concern + applyWriteConcern(cmd, { db: this }, options); + + // Ensure primary only + const finalOptions = Object.assign({}, this.s.options, { + readPreference: ReadPreference.PRIMARY + }); + + if (options.session) { + finalOptions.session = options.session; + } + + return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]); +}; + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, collections, [this, options, callback]); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.readPreference = resolveReadPreference(options); + + return executeOperation(this.s.topology, executeDbAdminCommand, [ + this, + selector, + options, + callback + ]); +}; + +/** + * Creates an index on the db and collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + return executeOperation(this.s.topology, createIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, ensureIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); + +Db.prototype.addChild = function(db) { + if (this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, addUser, [this, username, password, options, callback]); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, removeUser, [this, username, options, callback]); +}; + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.setProfilingLevel = function(level, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, setProfilingLevel, [this, level, options, callback]); +}; + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Query the system.profile collection directly. + */ +Db.prototype.profilingInfo = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, profilingInfo, [this, options, callback]); +}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.profilingLevel = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, profilingLevel, [this, options, callback]); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.s.topology, indexInformation, [this, name, options, callback]); +}; + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Db.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Db.prototype.getLogger = function() { + return this.s.logger; +}; + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + +module.exports = Db; diff --git a/node_modules/mongodb/lib/error.js b/node_modules/mongodb/lib/error.js new file mode 100644 index 0000000..03b555a --- /dev/null +++ b/node_modules/mongodb/lib/error.js @@ -0,0 +1,43 @@ +'use strict'; + +const MongoNetworkError = require('mongodb-core').MongoNetworkError; +const mongoErrorContextSymbol = require('mongodb-core').mongoErrorContextSymbol; + +const GET_MORE_NON_RESUMABLE_CODES = new Set([ + 136, // CappedPositionLost + 237, // CursorKilled + 11601 // Interrupted +]); + +// From spec@https://github.com/mongodb/specifications/blob/35e466ddf25059cb30e4113de71cdebd3754657f/source/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the following error codes +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// - a server error response with an error message containing the substring "not master" or "node is recovering" +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. + +function isGetMoreError(error) { + if (error[mongoErrorContextSymbol]) { + return error[mongoErrorContextSymbol].isGetMore; + } +} + +function isResumableError(error) { + if (!isGetMoreError(error)) { + return false; + } + + return !!( + error instanceof MongoNetworkError || + !GET_MORE_NON_RESUMABLE_CODES.has(error.code) || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/node_modules/mongodb/lib/gridfs-stream/download.js b/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 0000000..9012602 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,415 @@ +'use strict'; + +var stream = require('stream'), + util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options] Optional settings. + * @param {Number} [options.sort] Optional sort for the file find query + * @param {Number} [options.skip] Optional skip for the file find query + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + return _this.s.cursor.close(function(error) { + if (error) { + return __handleError(_this, error); + } + _this.emit('close'); + }); + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.length !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = + 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += buf.length; + + if (buf.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + if (expectedN === _this.s.expectedEnd && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.bytesToTrim; + } + + // If the remaining amount of data left is < chunkSize read the right amount of data + if (_this.s.options.end && _this.s.options.end - _this.s.bytesToSkip < buf.length) { + sliceEnd = _this.s.options.end - _this.s.bytesToSkip; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); + + var filter = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (self.s.options && self.s.options.start != null) { + var skip = Math.floor(self.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); + + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'greater than stream end (' + + options.end + + ')' + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error( + 'Stream end (' + + options.end + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); + } + + var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/node_modules/mongodb/lib/gridfs-stream/index.js b/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 0000000..9d64a84 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,358 @@ +'use strict'; + +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); +var executeOperation = require('../utils').executeOperation; + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || Promise + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options] Optional settings. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + return executeOperation(this.s.db.s.topology, _delete, [this, id, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options] Optional settings for cursor + * @param {number} [options.batchSize] Optional batch size for cursor + * @param {number} [options.limit] Optional limit for cursor + * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip] Optional skip for cursor + * @param {object} [options.sort] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + return executeOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + return executeOperation(this.s.db.s.topology, _drop, [this, callback], { + skipSessions: true + }); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +GridFSBucket.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/node_modules/mongodb/lib/gridfs-stream/upload.js b/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 0000000..adbba41 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,538 @@ +'use strict'; + +var core = require('mongodb-core'); +var crypto = require('crypto'); +var stream = require('stream'); +var util = require('util'); +var Buffer = require('safe-buffer').Buffer; + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {string|number|object} [options.id] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes + * @param {number} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {number} [options.j] The journal write concern + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.md5 = !options.disableMD5 && crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if (typeof callback === 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if (typeof chunk === 'function') { + (callback = chunk), (chunk = null), (encoding = null); + } else if (typeof encoding === 'function') { + (callback = encoding), (encoding = null); + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.done) return true; + if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { + // Set done so we dont' trigger duplicate createFilesDoc + _this.done = true; + // Create a new files doc + var filesDoc = createFilesDoc( + _this.id, + _this.length, + _this.chunkSizeBytes, + _this.md5 && _this.md5.digest('hex'), + _this.filename, + _this.options.contentType, + _this.options.aliases, + _this.options.metadata + ); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + filename: filename + }; + + if (md5) { + ret.md5 = md5; + } + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + if (_this.md5) { + _this.md5.update(_this.bufToStore); + } + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = Buffer.alloc(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + if (_this.md5) { + _this.md5.update(remnant); + } + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if (typeof callback === 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} diff --git a/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..c29bba0 --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,236 @@ +'use strict'; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +var Buffer = require('safe-buffer').Buffer; + +/** + * 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 = function(file, mongoObject, writeConcern) { + if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || { w: 1 }; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if (typeof mongoObjectFinal.data === 'string') { + var buffer = Buffer.alloc(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if (Array.isArray(mongoObjectFinal.data)) { + buffer = Buffer.alloc(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { + 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, data.length, 'binary'); + 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 = Buffer.alloc(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(options, callback) { + var self = this; + if (typeof options === 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if (err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for (var name in options) writeOptions[name] = options[name]; + for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if (self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = { forceServerObjectId: true }; + for (var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { + 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: + * + *

+ *        {
+ *          '_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
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + files_id: this.file.fileId, + n: this.chunkNumber, + data: this.data + }; + // If we are saving using a specific ObjectId + if (this.objectId != null) mongoObject._id = this.objectId; + + 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 * 255; + +module.exports = Chunk; diff --git a/node_modules/mongodb/lib/gridfs/grid_store.js b/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..4b5eb5e --- /dev/null +++ b/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1907 @@ +'use strict'; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * const GridStore = require('mongodb').GridStore; + * const ObjectID = require('mongodb').ObjectID; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * const gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * client.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +const Chunk = require('./chunk'); +const ObjectID = require('mongodb-core').BSON.ObjectID; +const ReadPreference = require('mongodb-core').ReadPreference; +const Buffer = require('safe-buffer').Buffer; +const fs = require('fs'); +const f = require('util').format; +const util = require('util'); +const MongoError = require('mongodb-core').MongoError; +const inherits = util.inherits; +const Duplex = require('stream').Duplex; +const shallowClone = require('../utils').shallowClone; +const executeOperation = require('../utils').executeOperation; +const deprecate = require('util').deprecate; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +const deprecationFn = deprecate(() => {}, +'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + deprecationFn(); + if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if (typeof options === 'undefined') options = {}; + // Handle mode + if (typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if (typeof mode === 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if (id && id._bsontype === 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if (typeof filename === 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? 'r' : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = + this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = + this.options.readPreference || db.options.readPreference || ReadPreference.primary; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = + this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary || Promise; + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, 'chunkSize', { + enumerable: true, + get: function() { + return this.internalChunkSize; + }, + set: function(value) { + if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, 'md5', { + enumerable: true, + get: function() { + return this.internalMd5; + } + }); + + Object.defineProperty(this, 'chunkNumber', { + enumerable: true, + get: function() { + return this.currentChunk && this.currentChunk.chunkNumber + ? this.currentChunk.chunkNumber + : null; + } + }); +}; + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { + throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); + } + + return executeOperation(this.db.s.topology, open, [this, options, callback], { + skipSessions: true + }); +}; + +var open = function(self, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if (self.mode === 'w' || self.mode === 'w+') { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position === this.length ? true : false; +}; + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, getc, [this, options, callback], { + skipSessions: true + }); +}; + +var getc = function(self, options, callback) { + if (self.eof()) { + callback(null, null); + } else if (self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +}; + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + var finalString = string.match(/\n$/) == null ? string + '\n' : string; + return executeOperation( + this.db.s.topology, + this.write.bind(this), + [finalString, options, callback], + { skipSessions: true } + ); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +}; + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.db.s.topology, + _writeNormal, + [this, data, close, options, callback], + { skipSessions: true } + ); +}; + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if (!this.writable) return; + this.readable = false; + if (this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +}; + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function(file, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, writeFile, [this, file, options, callback], { + skipSessions: true + }); +}; + +var writeFile = function(self, file, options, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function(err, fd) { + if (err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function(err, self) { + if (err) return callback(err, self); + + fs.fstat(file, function(err, stats) { + if (err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + // Allocate the buffer + var _buffer = Buffer.alloc(self.chunkSize); + // Read the file + fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { + if (err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, { n: index++ }, self.writeConcern); + chunk.write(data.slice(0, bytesRead), function(err, chunk) { + if (err) return callback(err, self); + + chunk.save({}, function(err) { + if (err) return callback(err, self); + + self.position = self.position + bytesRead; + + // Point to current chunk + self.currentChunk = chunk; + + if (offset >= stats.size) { + fs.close(file, function(err) { + if (err) return callback(err); + + self.close(function(err) { + if (err) return callback(err, self); + return callback(null, self); + }); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + }; + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, close, [this, options, callback], { + skipSessions: true + }); +}; + +var close = function(self, options, callback) { + if (self.mode[0] === 'w') { + // Set up options + options = Object.assign({}, self.writeConcern, options); + + if (self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if (err && typeof callback === 'function') return callback(err); + + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + // Build the mongo object + if (self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + }); + } + } else if (self.mode[0] === 'r') { + if (typeof callback === 'function') callback(null, null); + } else { + if (typeof callback === 'function') + callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); + return this.db.collection(this.root + '.chunks'); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, unlink, [this, options, callback], { + skipSessions: true + }); +}; + +var unlink = function(self, options, callback) { + deleteChunks(self, function(err) { + if (err !== null) { + err.message = 'at deleteChunks: ' + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if (err !== null) { + err.message = 'at collection: ' + err.message; + return callback(err); + } + + collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); + return this.db.collection(this.root + '.files'); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : '\n'; + separator = separator || '\n'; + options = args.length ? args.shift() : {}; + + return executeOperation(this.db.s.topology, readlines, [this, separator, options, callback], { + skipSessions: true + }); +}; + +var readlines = function(self, separator, options, callback) { + self.read(function(err, data) { + if (err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for (var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation(this.db.s.topology, rewind, [this, options, callback], { + skipSessions: true + }); +}; + +var rewind = function(self, options, callback) { + if (self.currentChunk.chunkNumber !== 0) { + if (self.mode[0] === 'w') { + deleteChunks(self, function(err) { + if (err) return callback(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if (err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeOperation(this.db.s.topology, read, [this, length, buffer, options, callback], { + skipSessions: true + }); +}; + +var read = function(self, length, buffer, options, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if (finalLength === 0 && finalBuffer.length === 0) + return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if (err) return callback(err); + + if (chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if (finalBuffer._index > 0) { + callback(null, finalBuffer); + } else { + callback( + MongoError.create({ + message: 'no chunks found for file, possibly corrupt', + driver: true + }), + null + ); + } + } + }); +}; + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if (typeof callback === 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + seekLocation = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeOperation( + this.db.s.topology, + seek, + [this, position, seekLocation, options, callback], + { skipSessions: true } + ); +}; + +var seek = function(self, position, seekLocation, options, callback) { + // Seek only supports read mode + if (self.mode !== 'r') { + return callback( + MongoError.create({ message: 'seek is only supported for mode r', driver: true }) + ); + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if (seekLocationFinal === GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if (seekLocationFinal === GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition / self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if (err) return callback(err, null); + if (chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = self.position % self.chunkSize; + callback(err, self); + }); + }; + + seekChunk(); +}; + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = + self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if (query != null) { + collection.findOne(query, options, function(err, doc) { + if (err) { + return error(err); + } + + // Check if the collection for the files exists otherwise prepare the new one + if (doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = + self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode !== 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; + return error( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename + ), + driver: true + }), + self + ); + } + + // Process the mode of the object + if (self.mode === 'r') { + nthChunk(self, 0, options, function(err, chunk) { + if (err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w' && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null + ? self.internalChunkSize + : self.options['chunk_size']; + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w') { + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if (self.mode === 'w') { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error(err) { + if (error.err) return; + callback((error.err = err)); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if (typeof close === 'function') { + callback = close; + close = null; + } + var finalClose = typeof close === 'boolean' ? close : false; + + if (self.mode !== 'w') { + callback( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename + ), + driver: true + }), + null + ); + } else { + if (self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while (leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + // If we have left over data write it + if (leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for (var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if (err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if (numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + _id: self.fileId, + filename: self.filename, + contentType: self.contentType, + length: self.position ? self.position : 0, + chunkSize: self.chunkSize, + uploadDate: self.uploadDate, + aliases: self.aliases, + metadata: self.metadata + }; + + var md5Command = { filemd5: self.fileId, root: self.root }; + self.db.command(md5Command, function(err, results) { + if (err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self + .chunkCollection() + .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { + if (err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if (self.fileId != null) { + self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { + if (err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** + * The collection to be used for holding the files and chunks collection. + * + * @classconstant DEFAULT_ROOT_COLLECTION + */ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** + * Default file mime type + * + * @classconstant DEFAULT_CONTENT_TYPE + */ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** + * Seek mode where the given length is absolute. + * + * @classconstant IO_SEEK_SET + */ +GridStore.IO_SEEK_SET = 0; + +/** + * Seek mode where the given length is an offset to the current read/write head. + * + * @classconstant IO_SEEK_CUR + */ +GridStore.IO_SEEK_CUR = 1; + +/** + * Seek mode where the given length is an offset to the end of the file. + * + * @classconstant IO_SEEK_END + */ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation( + db.s.topology, + exists, + [db, fileIdObject, rootCollection, options, callback], + { skipSessions: true } + ); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + // Build query + var query = + typeof fileIdObject === 'string' || + Object.prototype.toString.call(fileIdObject) === '[object RegExp]' + ? { filename: fileIdObject } + : { _id: fileIdObject }; // Attempt to locate file + + // We have a specific query + if ( + fileIdObject != null && + typeof fileIdObject === 'object' && + Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' + ) { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, { readPreference: readPreference }, function(err, item) { + if (err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation(db.s.topology, list, [db, rootCollection, options, callback], { + skipSessions: true + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if (rootCollection != null && typeof rootCollection === 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.primary; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + collection.find({}, { readPreference: readPreference }, function(err, cursor) { + if (err) return callback(err); + + cursor.each(function(err, item) { + if (item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeOperation( + db.s.topology, + readStatic, + [db, name, length, offset, options, callback], + { skipSessions: true } + ); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + // Make sure we are not reading out of bounds + if (offset && offset >= gridStore.length) + return callback('offset larger than size of file', null); + if (length && length > gridStore.length) + return callback('length is larger than the size of the file', null); + if (offset && length && offset + length > gridStore.length) + return callback('offset and length is larger than the size of the file', null); + + if (offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if (err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeOperation( + db.s.topology, + readlinesStatic, + [db, name, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? '\n' : separator; + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options] Optional settings. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { + skipSessions: true + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if (names.constructor === Array) { + var tc = 0; + for (var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if (--tc === 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, 'w', options).open(function(err, gridStore) { + if (err) return callback(err); + deleteChunks(gridStore, function(err) { + if (err) return callback(err); + gridStore.collection(function(err, collection) { + if (err) return callback(err); + collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, options, callback) { + // If we have a buffer write it using the writeBuffer method + if (Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); + } +}; + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if (options.w != null) finalOptions.w = options.w; + if (options.journal === true) finalOptions.j = options.journal; + if (options.j === true) finalOptions.j = options.j; + if (options.fsync === true) finalOptions.fsync = options.fsync; + if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +}; + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = { w: 1 }; + options = options || {}; + + // Local options verification + if ( + options.w != null || + typeof options.j === 'boolean' || + typeof options.journal === 'boolean' || + typeof options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(options); + } else if (options.safe != null && typeof options.safe === 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if (typeof options.safe === 'boolean') { + finalOptions = { w: options.safe ? 1 : 0 }; + } else if ( + self.options.w != null || + typeof self.options.j === 'boolean' || + typeof self.options.journal === 'boolean' || + typeof self.options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(self.options); + } else if ( + self.safe && + (self.safe.w != null || + typeof self.safe.j === 'boolean' || + typeof self.safe.journal === 'boolean' || + typeof self.safe.fsync === 'boolean') + ) { + finalOptions = _setWriteConcernHash(self.safe); + } else if (typeof self.safe === 'boolean') { + finalOptions = { w: self.safe ? 1 : 0 }; + } + + // Ensure we don't have an invalid combination of write concerns + if ( + finalOptions.w < 1 && + (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) + ) + throw MongoError.create({ + message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', + driver: true + }); + + // Return the options + return finalOptions; +}; + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +}; + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if (!self.gs.isOpen) { + self.gs.open(function(err) { + if (err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +}; + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if (err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if (self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if (buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if (buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if (self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + }; + + // Set read length + var length = + self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if (!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if (err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +}; + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +}; + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if (self.endCalled) + return self.emit( + 'error', + MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) + ); + // Do we have to open the gridstore + if (!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +}; + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if (chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); + }); + } + + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); +}; + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/node_modules/mongodb/lib/mongo_client.js b/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..b1a3bed --- /dev/null +++ b/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,472 @@ +'use strict'; + +const ChangeStream = require('./change_stream'); +const Db = require('./db'); +const EventEmitter = require('events').EventEmitter; +const executeOperation = require('./utils').executeOperation; +const handleCallback = require('./utils').handleCallback; +const inherits = require('util').inherits; +const MongoError = require('mongodb-core').MongoError; + +// Operations +const connectOp = require('./operations/mongo_client_ops').connectOp; +const logout = require('./operations/mongo_client_ops').logout; +const validOptions = require('./operations/mongo_client_ops').validOptions; + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * + * @example + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.useNewUrlParser=false] Determines whether or not to use the new url parser + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {MongoClient} a MongoClient instance + */ +function MongoClient(url, options) { + if (!(this instanceof MongoClient)) return new MongoClient(url, options); + // Set up event emitter + EventEmitter.call(this); + + // The internal state + this.s = { + url: url, + options: options || {}, + promiseLibrary: null, + dbCache: {}, + sessions: [] + }; + + // Get the promiseLibrary + const promiseLibrary = this.s.options.promiseLibrary || Promise; + + // Add the promise to the internal state + this.s.promiseLibrary = promiseLibrary; +} + +/** + * @ignore + */ +inherits(MongoClient, EventEmitter); + +/** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {MongoClient} client The connected client. + */ + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.connect = function(callback) { + // Validate options object + const err = validOptions(this.s.options); + + if (typeof callback === 'string') { + throw new TypeError('`connect` only accepts a callback'); + } + + return executeOperation(this, connectOp, [this, err, callback], { + skipSessions: true + }); +}; + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options] Optional settings. + * @param {string} [options.dbName] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.logout = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Establish the correct database name + const dbName = this.s.options.authSource ? this.s.options.authSource : this.s.options.dbName; + + return executeOperation(this, logout, [this, dbName, callback], { + skipSessions: true + }); +}; + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.close = function(force, callback) { + if (typeof force === 'function') (callback = force), (force = false); + + // Close the topology connection + if (this.topology) { + this.topology.close(force); + } + // Emit close event + this.emit('close', this); + + // Fire close event on any cached db instances + for (const name in this.s.dbCache) { + this.s.dbCache[name].emit('close'); + } + + // Remove listeners after emit + this.removeAllListeners('close'); + + // Callback after next event loop tick + if (typeof callback === 'function') + return process.nextTick(() => { + handleCallback(callback, null); + }); + + // Return dummy promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); +}; + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +MongoClient.prototype.db = function(dbName, options) { + options = options || {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.s.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this.s.options, options); + + // Do we have the db in the cache already + if (this.s.dbCache[dbName] && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // If no topology throw an error message + if (!this.topology) { + throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); + } + + // Return the db object + const db = new Db(dbName, this.topology, finalOptions); + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +/** + * Check if MongoClient is connected + * + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {boolean} + */ +MongoClient.prototype.isConnected = function(options) { + options = options || {}; + + if (!this.topology) return false; + return this.topology.isConnected(options); +}; + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {string} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : null; + options = options || {}; + + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + return mongoClient.connect(callback); +}; + +/** + * Starts a new session on the server + * + * @param {SessionOptions} [options] optional settings for a driver session + * @return {ClientSession} the newly established session + */ +MongoClient.prototype.startSession = function(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoError('Must connect to a server before calling this method'); + } + + if (!this.topology.hasSessionSupport()) { + throw new MongoError('Current topology does not support sessions'); + } + + return this.topology.startSession(options, this.s.options); +}; + +/** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) + * + * @param {Object} [options] Optional settings to be appled to implicitly created session + * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` + * @return {Promise} + */ +MongoClient.prototype.withSession = function(options, operation) { + if (typeof options === 'function') (operation = options), (options = undefined); + const session = this.startSession(options); + + let cleanupHandler = (err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + throw new ReferenceError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }; + + try { + const result = operation(session); + return Promise.resolve(result) + .then(result => cleanupHandler(null, result)) + .catch(err => cleanupHandler(err, null, { throw: true })); + } catch (err) { + return cleanupHandler(err, null, { throw: false }); + } +}; +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, + * and config databases. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtClusterTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +MongoClient.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the mongo client logger + * @method + * @return {Logger} return the mongo client logger + * @ignore + */ +MongoClient.prototype.getLogger = function() { + return this.s.options.logger; +}; + +module.exports = MongoClient; diff --git a/node_modules/mongodb/lib/operations/admin_ops.js b/node_modules/mongodb/lib/operations/admin_ops.js new file mode 100644 index 0000000..b08071c --- /dev/null +++ b/node_modules/mongodb/lib/operations/admin_ops.js @@ -0,0 +1,62 @@ +'use strict'; + +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; + +/** + * Get ReplicaSet status + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function replSetGetStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); +} + +/** + * Retrieve this db's server status. + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback + */ +function serverStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); +} + +/** + * Validate an existing collection + * + * @param {Admin} a collection instance. + * @param {string} collectionName The name of the collection to validate. + * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function validateCollection(admin, collectionName, options, callback) { + const command = { validate: collectionName }; + const keys = Object.keys(options); + + // Decorate command with extra options + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + executeCommand(admin.s.db, command, options, (err, doc) => { + if (err != null) return callback(err, null); + + 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); + }); +} + +module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/node_modules/mongodb/lib/operations/collection_ops.js b/node_modules/mongodb/lib/operations/collection_ops.js new file mode 100644 index 0000000..e828584 --- /dev/null +++ b/node_modules/mongodb/lib/operations/collection_ops.js @@ -0,0 +1,1479 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const checkCollectionName = require('../utils').checkCollectionName; +const Code = require('mongodb-core').BSON.Code; +const createIndexDb = require('./db_ops').createIndex; +const decorateCommand = require('../utils').decorateCommand; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const ensureIndexDb = require('./db_ops').ensureIndex; +const evaluate = require('./db_ops').evaluate; +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const resolveReadPreference = require('../utils').resolveReadPreference; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; +const isObject = require('../utils').isObject; +const Long = require('mongodb-core').BSON.Long; +const MongoError = require('mongodb-core').MongoError; +const ReadPreference = require('mongodb-core').ReadPreference; +const toError = require('../utils').toError; + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +const groupFunction = + 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +/** + * Perform a bulkWrite operation. See Collection.prototype.bulkWrite for more information. + * + * @method + * @param {Collection} a Collection instance. + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. See Collection.prototype.bulkWrite for a list of options. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + */ +function bulkWrite(coll, operations, options, callback) { + // Add ignoreUndfined + if (coll.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = coll.s.options.ignoreUndefined; + } + + // Create the bulk operation + const bulk = + options.ordered === true || options.ordered == null + ? coll.initializeOrderedBulkOp(options) + : coll.initializeUnorderedBulkOp(options); + + // Do we have a collation + let collation = false; + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + // Get the operation type + const key = Object.keys(operations[i])[0]; + // Check if we have a collation + if (operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err, null); + } + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + const capabilities = coll.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + // Execute the bulk + bulk.execute(writeCon, finalOptions, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err, null); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + const inserted = r.getInsertedIds(); + // Map inserted ids + for (let i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + const upserted = r.getUpsertedIds(); + // Map upserted ids + for (let i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); +} + +// Check the update operation to ensure it has atomic operators. +function checkForAtomicOperators(update) { + const keys = Object.keys(update); + + // same errors as the server would give for update doc lacking atomic operators + if (keys.length === 0) { + return toError('The update operation document must contain at least one atomic operator.'); + } + + if (keys[0][0] !== '$') { + return toError('the update operation document must contain atomic operators.'); + } +} + +/** + * Count the number of documents in the collection that match the query. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count for a list of options. + * @param {Collection~countCallback} [callback] The command result callback + */ +function count(coll, query, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + options.collectionName = coll.s.name; + + options.readPreference = resolveReadPreference(options, { + db: coll.s.db, + collection: coll + }); + + let cmd; + try { + cmd = buildCountCommand(coll, query, options); + } catch (err) { + return callback(err); + } + + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +function countDocuments(coll, query, options, callback) { + const skip = options.skip; + const limit = options.limit; + options = Object.assign({}, options); + + const pipeline = [{ $match: query }]; + + // Add skip and limit if defined + if (typeof skip === 'number') { + pipeline.push({ $skip: skip }); + } + + if (typeof limit === 'number') { + pipeline.push({ $limit: limit }); + } + + pipeline.push({ $group: { _id: null, n: { $sum: 1 } } }); + + delete options.limit; + delete options.skip; + + coll.aggregate(pipeline, options).toArray((err, docs) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, docs.length ? docs[0].n : 0); + }); +} + +/** + * Build the count command. + * + * @method + * @param {collectionOrCursor} an instance of a collection or cursor + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. + */ +function buildCountCommand(collectionOrCursor, query, options) { + const skip = options.skip; + const limit = options.limit; + let hint = options.hint; + const maxTimeMS = options.maxTimeMS; + query = query || {}; + + // Final query + const cmd = { + count: options.collectionName, + query: query + }; + + // check if collectionOrCursor is a cursor by using cursor.s.numberOfRetries + if (collectionOrCursor.s.numberOfRetries) { + if (collectionOrCursor.s.options.hint) { + hint = collectionOrCursor.s.options.hint; + } else if (collectionOrCursor.s.cmd.hint) { + hint = collectionOrCursor.s.cmd.hint; + } + decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.s.cmd); + } else { + decorateWithCollation(cmd, collectionOrCursor, options); + } + + // Add limit, skip and maxTimeMS if defined + if (typeof skip === 'number') cmd.skip = skip; + if (typeof limit === 'number') cmd.limit = limit; + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + if (hint) cmd.hint = hint; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, collectionOrCursor); + + return cmd; +} + +/** + * Create an index on the db and collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndex(coll, fieldOrSpec, options, callback) { + createIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); +} + +/** + * Create multiple indexes in the collection. This method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * + * @method + * @param {Collection} a Collection instance. + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndexes(coll, indexSpecs, options, callback) { + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.s.name, + indexes: indexSpecs + }, + options, + callback + ); +} + +function deleteCallback(err, r, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.deletedCount = r.result.n; + if (callback) callback(null, r); +} + +/** + * Delete multiple documents from the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. See Collection.prototype.deleteMany for a list of options. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + */ +function deleteMany(coll, filter, options, callback) { + options.single = false; + + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); +} + +/** + * Delete a single document from the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. See Collection.prototype.deleteOne for a list of options. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + */ +function deleteOne(coll, filter, options, callback) { + options.single = true; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); +} + +/** + * Return a list of distinct values for the given key across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function distinct(coll, key, query, options, callback) { + // maxTimeMS option + const maxTimeMS = options.maxTimeMS; + + // Distinct command + const cmd = { + distinct: coll.s.name, + key: key, + query: query + }; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Add maxTimeMS if defined + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +/** + * Drop an index from this collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. See Collection.prototype.dropIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function dropIndex(coll, indexName, options, callback) { + // Delete index command + const cmd = { dropIndexes: coll.s.name, index: indexName }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (typeof callback !== 'function') return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +/** + * Drop all indexes from this collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.dropIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function dropIndexes(coll, options, callback) { + dropIndex(coll, '*', options, err => { + if (err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +/** + * Ensure that an index exists. If the index does not exist, this function creates it. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function ensureIndex(coll, fieldOrSpec, options, callback) { + ensureIndexDb(coll.s.db, coll.s.name, fieldOrSpec, options, callback); +} + +/** + * Find and update a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +function findAndModify(coll, query, sort, doc, options, callback) { + // Create findAndModify command object + const queryObject = { + findAndModify: coll.s.name, + query: query + }; + + sort = formattedOrderClause(sort); + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + delete options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (finalOptions.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + finalOptions.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, finalOptions); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); +} + +/** + * Find and remove a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. See Collection.prototype.findAndRemove for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated use findOneAndDelete instead + */ +function findAndRemove(coll, query, sort, options, callback) { + // Add the remove option + options.remove = true; + // Execute the callback + findAndModify(coll, query, sort, null, options, callback); +} + +/** + * Fetch the first document that matches the query. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. See Collection.prototype.findOne for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function findOne(coll, query, options, callback) { + const cursor = coll + .find(query, options) + .limit(-1) + .batchSize(1); + + // Return the item + cursor.next((err, item) => { + if (err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +/** + * Find a document and delete it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndDelete for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndDelete(coll, filter, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.remove = true; + // Execute find and Modify + findAndModify(coll, filter, options.sort, null, finalOptions, callback); +} + +/** + * Find a document and replace it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndReplace for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndReplace(coll, filter, replacement, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; + finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; + + // Execute findAndModify + findAndModify(coll, filter, options.sort, replacement, finalOptions, callback); +} + +/** + * Find a document and update it in one atomic operation. This requires a write lock for the duration of the operation. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. See Collection.prototype.findOneAndUpdate for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + */ +function findOneAndUpdate(coll, filter, update, options, callback) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; + finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; + + // Execute findAndModify + findAndModify(coll, filter, options.sort, update, finalOptions, callback); +} + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function geoHaystackSearch(coll, x, y, options, callback) { + // Build command object + let commandObject = { + geoSearch: coll.s.name, + near: [x, y] + }; + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, res) => { + if (err) return handleCallback(callback, err); + if (res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +/** + * Run a group command across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. + */ +function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if (command) { + const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); + + const selector = { + group: { + ns: coll.s.name, + $reduce: reduceFunction, + cond: condition, + initial: initial, + out: 'inline' + } + }; + + // if finalize is defined + if (finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { + selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); + } else { + const hash = {}; + keys.forEach(key => { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Do we have a readConcern specified + decorateWithReadConcern(selector, coll, options); + + // Have we specified collation + try { + decorateWithCollation(selector, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, selector, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; + + scope.ns = coll.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Retrieve all the indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexes(coll, options, callback) { + options = Object.assign({}, { full: true }, options); + indexInformationDb(coll.s.db, coll.s.name, options, callback); +} + +/** + * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexExists(coll, indexes, options, callback) { + indexInformation(coll, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieve this collection's index info. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexInformation(coll, options, callback) { + indexInformationDb(coll.s.db, coll.s.name, options, callback); +} + +function insertDocuments(coll, docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If keep going set unordered + if (finalOptions.keepGoing === true) finalOptions.ordered = false; + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // File inserts + coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Insert a single document into the collection. See Collection.prototype.insertOne for more information. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. See Collection.prototype.insertOne for a list of options. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + */ +function insertOne(coll, doc, options, callback) { + if (Array.isArray(doc)) { + return callback( + MongoError.create({ message: 'doc parameter must be an object', driver: true }) + ); + } + + insertDocuments(coll, [doc], options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + // Workaround for pre 2.6 servers + if (r == null) return callback(null, { result: { ok: 1 } }); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if (callback) callback(null, r); + }); +} + +/** + * Determine whether the collection is a capped collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.isCapped for a list of options. + * @param {Collection~resultCallback} [callback] The results callback + */ +function isCapped(coll, options, callback) { + optionsOp(coll, options, (err, document) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, !!(document && document.capped)); + }); +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function mapReduce(coll, map, reduce, options, callback) { + const mapCommandHash = { + mapreduce: coll.s.name, + map: map, + reduce: reduce + }; + + // Exclusion list + const exclusionList = ['readPreference', 'session', 'bypassDocumentValidation']; + + // Add any other options passed in + for (let n in options) { + if ('scope' === n) { + mapCommandHash[n] = processScope(options[n]); + } else { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + } + + options = Object.assign({}, options); + + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // If we have a read preference and inline is not set as output fail hard + if ( + options.readPreference !== false && + options.readPreference !== 'primary' && + options['out'] && + (options['out'].inline !== 1 && options['out'] !== 'inline') + ) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { + if (err) return handleCallback(callback, err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + const stats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + const Db = require('../db'); + collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, { collection: collection, stats: stats }); + }); +} + +/** + * Return the options of the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.options for a list of options. + * @param {Collection~resultCallback} [callback] The results callback + */ +function optionsOp(coll, opts, callback) { + coll.s.db.listCollections({ name: coll.s.name }, opts).toArray((err, collections) => { + if (err) return handleCallback(callback, err); + if (collections.length === 0) { + return handleCallback( + callback, + MongoError.create({ message: `collection ${coll.s.namespace} not found`, driver: true }) + ); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +/** + * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are + * no ordering guarantees for returned results. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + */ +function parallelCollectionScan(coll, options, callback) { + // Create command object + const commandObject = { + parallelCollectionScan: coll.s.name, + numCursors: options.numCursors + }; + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Store the raw value + const raw = options.raw; + delete options['raw']; + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result == null) + return handleCallback( + callback, + new Error('no result returned for parallelCollectionScan'), + null + ); + + options = Object.assign({ explicitlyIgnoreSession: true }, options); + + const cursors = []; + // Add the raw back to the option + if (raw) options.raw = raw; + // Create command cursors for each item + for (let i = 0; i < result.cursors.length; i++) { + const rawId = result.cursors[i].cursor.id; + // Convert cursorId to Long if needed + const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(coll.s.topology.cursor(coll.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +// modifies documents before being inserted or updated +function prepareDocs(coll, docs, options) { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (forceServerObjectId !== true && doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope(scope) { + if (!isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + + const keys = Object.keys(scope); + let key; + const new_scope = {}; + + for (let i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if ('function' === typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Reindex all indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.reIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function reIndex(coll, options, callback) { + // Reindex + const cmd = { reIndex: coll.s.name }; + + // Execute the command + executeCommand(coll.s.db, cmd, options, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +function removeDocuments(coll, selector, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}); + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If selector is null set empty + if (selector == null) selector = {}; + + // Build the op + const op = { q: selector, limit: 0 }; + if (options.single) { + op.limit = 1; + } else if (finalOptions.retryWrites) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the remove + coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Rename the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. See Collection.prototype.rename for a list of options. + * @param {Collection~collectionResultCallback} [callback] The results callback + */ +function rename(coll, newName, options, callback) { + const Collection = require('../collection'); + // Check the collection name + checkCollectionName(newName); + // Build the command + const renameCollection = `${coll.s.dbName}.${coll.s.name}`; + const toCollection = `${coll.s.dbName}.${newName}`; + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute against admin + executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { + if (err) return handleCallback(callback, err, null); + // We have an error + if (doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback( + callback, + null, + new Collection( + coll.s.db, + coll.s.topology, + coll.s.dbName, + newName, + coll.s.pkFactory, + coll.s.options + ) + ); + } catch (err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +/** + * Replace a document in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. See Collection.prototype.replaceOne for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function replaceOne(coll, filter, doc, options, callback) { + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(coll, filter, doc, options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; + if (callback) callback(null, r); + }); +} + +/** + * Save a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to save + * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +function save(coll, doc, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern( + Object.assign({}, options), + { db: coll.s.db, collection: coll }, + options + ); + // Establish if we need to perform an insert or update + if (doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(coll, [doc], finalOptions, (err, result) => { + if (callback == null) return; + if (doc == null) return handleCallback(callback, null, null); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +/** + * Get all the collection statistics. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + * @param {Collection~resultCallback} [callback] The collection result callback + */ +function stats(coll, options, callback) { + // Build command object + const commandObject = { + collStats: coll.s.name + }; + + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(options, { db: coll.s.db, collection: coll }); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, callback); +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +function updateDocuments(coll, selector, document, options, callback) { + if ('function' === typeof options) (callback = options), (options = null); + if (options == null) options = {}; + if (!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if (selector == null || typeof selector !== 'object') + return callback(toError('selector must be a valid JavaScript object')); + if (document == null || typeof document !== 'object') + return callback(toError('document must be a valid JavaScript object')); + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // Execute the operation + const op = { q: selector, u: document }; + op.upsert = options.upsert !== void 0 ? !!options.upsert : false; + op.multi = options.multi !== void 0 ? !!options.multi : false; + + if (finalOptions.arrayFilters) { + op.arrayFilters = finalOptions.arrayFilters; + delete finalOptions.arrayFilters; + } + + if (finalOptions.retryWrites && op.multi) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Update options + coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Update multiple documents in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. See Collection.prototype.updateMany for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function updateMany(coll, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); +} + +/** + * Update a single document in the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. See Collection.prototype.updateOne for a list of options. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + */ +function updateOne(coll, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); +} + +module.exports = { + bulkWrite, + checkForAtomicOperators, + count, + countDocuments, + buildCountCommand, + createIndex, + createIndexes, + deleteMany, + deleteOne, + distinct, + dropIndex, + dropIndexes, + ensureIndex, + findAndModify, + findAndRemove, + findOne, + findOneAndDelete, + findOneAndReplace, + findOneAndUpdate, + geoHaystackSearch, + group, + indexes, + indexExists, + indexInformation, + insertOne, + isCapped, + mapReduce, + optionsOp, + parallelCollectionScan, + prepareDocs, + reIndex, + removeDocuments, + rename, + replaceOne, + save, + stats, + updateDocuments, + updateMany, + updateOne +}; diff --git a/node_modules/mongodb/lib/operations/cursor_ops.js b/node_modules/mongodb/lib/operations/cursor_ops.js new file mode 100644 index 0000000..5c0c093 --- /dev/null +++ b/node_modules/mongodb/lib/operations/cursor_ops.js @@ -0,0 +1,242 @@ +'use strict'; + +const buildCountCommand = require('./collection_ops').buildCountCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('mongodb-core').MongoError; +const push = Array.prototype.push; + +/** + * Get the count of documents for this cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to count. + * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. + * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. + * @param {Cursor~countResultCallback} [callback] The result callback. + */ +function count(cursor, applySkipLimit, opts, callback) { + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (opts.readPreference) { + cursor.setReadPreference(opts.readPreference); + } + + if ( + typeof opts.maxTimeMS !== 'number' && + cursor.s.cmd && + typeof cursor.s.cmd.maxTimeMS === 'number' + ) { + opts.maxTimeMS = cursor.s.cmd.maxTimeMS; + } + + let options = {}; + options.skip = opts.skip; + options.limit = opts.limit; + options.hint = opts.hint; + options.maxTimeMS = opts.maxTimeMS; + + // Command + const delimiter = cursor.s.ns.indexOf('.'); + options.collectionName = cursor.s.ns.substr(delimiter + 1); + + let command; + try { + command = buildCountCommand(cursor, cursor.s.cmd.query, options); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.s.topology.command( + `${cursor.s.ns.substr(0, delimiter)}.$cmd`, + command, + cursor.s.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); +} + +/** + * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. + * + * @method + * @deprecated + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} callback The result callback. + */ +function each(cursor, callback) { + const Cursor = require('../cursor'); + + if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); + if (cursor.isNotified()) return; + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === Cursor.INIT) cursor.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + let fn = null; + // Trampoline all the entries + if (cursor.bufferedCount() > 0) { + while ((fn = loop(cursor, callback))) fn(cursor, callback); + each(cursor, callback); + } else { + cursor.next((err, item) => { + if (err) return handleCallback(callback, err); + if (item == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); + } + + if (handleCallback(callback, null, item) === false) return; + each(cursor, callback); + }); + } +} + +/** + * Check if there is any document still available in the cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function hasNext(cursor, callback) { + const Cursor = require('../cursor'); + + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +function loop(cursor, callback) { + // No more items we are done + if (cursor.bufferedCount() === 0) return; + // Get the next document + cursor._next(callback); + // Loop + return loop; +} + +/** + * Get the next available document from the cursor. Returns null if no more documents are available. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function next(cursor, callback) { + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + const Cursor = require('../cursor'); + + if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { + try { + cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = Cursor.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +/** + * Returns an array of documents. See Cursor.prototype.toArray for more information. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + */ +function toArray(cursor, callback) { + const Cursor = require('../cursor'); + + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = Cursor.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); +} + +module.exports = { count, each, hasNext, next, toArray }; diff --git a/node_modules/mongodb/lib/operations/db_ops.js b/node_modules/mongodb/lib/operations/db_ops.js new file mode 100644 index 0000000..3795f8b --- /dev/null +++ b/node_modules/mongodb/lib/operations/db_ops.js @@ -0,0 +1,986 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('mongodb-core').BSON.Code; +const resolveReadPreference = require('../utils').resolveReadPreference; +const crypto = require('crypto'); +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('mongodb-core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; +const ReadPreference = require('mongodb-core').ReadPreference; +const toError = require('../utils').toError; +const CONSTANTS = require('../constants'); + +const count = require('./collection_ops').count; +const findOne = require('./collection_ops').findOne; +const remove = require('./collection_ops').remove; +const updateOne = require('./collection_ops').updateOne; + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +// Filter out any write concern options +const illegalCommandFields = [ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'strict', + 'serializeFunctions', + 'pkFactory', + 'raw', + 'readPreference', + 'session' +]; + +/** + * Add a user to the database. + * @method + * @param {Db} db The Db instance on which to add a user. + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function addUser(db, username, password, options, callback) { + const Db = require('../db'); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + executeAuthCreateUserCommand(db, username, password, options, (err, r) => { + // We need to perform the backward compatible insert operation + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + const userPassword = md5.digest('hex'); + + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + count(collection, {}, finalOptions, (err, count) => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); + collection.find({ user: username }, findOptions).toArray(err => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + updateOne( + collection, + { user: username }, + { $set: { user: username, pwd: userPassword } }, + finalOptions, + err => { + if (count === 0 && err) + return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + } + ); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db} db The Db instance on which to fetch collections. + * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. + * @param {Db~collectionsResultCallback} [callback] The results callback + */ +function collections(db, options, callback) { + const Collection = require('../collection'); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.s.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); +} + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {Db} db The Db instance on which to create the collection. + * @param {string} name The collection name to create. + * @param {object} [options] Optional settings. See Db.prototype.createCollection for a list of options. + * @param {Db~collectionResultCallback} [callback] The results callback + */ +function createCollection(db, name, options, callback) { + const Collection = require('../collection'); + + // Get the write concern options + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, finalOptions, { nameOnly: true }); + + // Check if we have the name + db + .listCollections({ name }, listCollectionOptions) + .setReadPreference(ReadPreference.PRIMARY) + .toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length > 0 && finalOptions.strict) { + return handleCallback( + callback, + MongoError.create({ + message: `Collection ${name} already exists. Currently in strict mode.`, + driver: true + }), + null + ); + } else if (collections.length > 0) { + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Create collection command + const cmd = { create: name }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db }, options); + + // Add all optional parameters + for (let n in options) { + if ( + options[n] != null && + typeof options[n] !== 'function' && + illegalCommandFields.indexOf(n) === -1 + ) { + cmd[n] = options[n]; + } + } + + // Force a primary read Preference + finalOptions.readPreference = ReadPreference.PRIMARY; + // Execute command + executeCommand(db, cmd, finalOptions, err => { + if (err) return handleCallback(callback, err); + handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.s.databaseName, name, db.s.pkFactory, options) + ); + }); + }); +} + +/** + * Creates an index on the db and collection. + * @method + * @param {Db} db The Db instance on which to create an index. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function createIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); + finalOptions = applyWriteConcern(finalOptions, { db }, options); + + // Ensure we have a callback + if (finalOptions.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { + if (err == null) return handleCallback(callback, err, result); + + /** + * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: + * 67 = 'CannotCreateIndex' (malformed index options) + * 85 = 'IndexOptionsConflict' (index already exists with different options) + * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) + * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) + * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) + */ + if ( + err.code === 67 || + err.code === 11000 || + err.code === 85 || + err.code === 86 || + err.code === 11600 || + err.code === 197 + ) { + return handleCallback(callback, err, result); + } + + // Create command + const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + db.s.topology.insert( + `${db.s.databaseName}.${CONSTANTS.SYSTEM_INDEX_COLLECTION}`, + doc, + finalOptions, + (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.writeErrors) + return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + } + ); + }); +} + +// Add listeners to topology +function createListener(db, e, object) { + function listener(err) { + if (object.listeners(e).length > 0) { + object.emit(e, err, db); + + // Emit on all associated db's if available + for (let i = 0; i < db.s.children.length; i++) { + db.s.children[i].emit(e, err, db.s.children[i]); + } + } + } + return listener; +} + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Db} db The Db instance on which to drop the collection. + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropCollection(db, name, options, callback) { + executeCommand(db, name, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); +} + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db} db The Db instance to drop. + * @param {Object} cmd The command document. + * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropDatabase(db, cmd, options, callback) { + executeCommand(db, cmd, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * Ensures that an index exists. If it does not, creates it. + * + * @method + * @param {Db} db The Db instance on which to ensure the index. + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function ensureIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern({}, { db }, options); + // Create command + const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); + const index_name = selector.name; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Merge primary readPreference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Check if the index already exists + indexInformation(db, name, finalOptions, (err, indexInformation) => { + if (err != null && err.code !== 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if (indexInformation == null || !indexInformation[index_name]) { + createIndex(db, name, fieldOrSpec, options, callback); + } else { + if (typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Db} db The Db instance. + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + */ +function evaluate(db, code, parameters, options, callback) { + let finalCode = code; + let finalParameters = []; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + let cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new ReadPreference(ReadPreference.PRIMARY); + + // Execute the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result && result.ok === 1) return handleCallback(callback, null, result.retval); + if (result) + return handleCallback( + callback, + MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), + null + ); + handleCallback(callback, err, result); + }); +} + +/** + * Execute a command + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeCommand(db, command, options, callback) { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.s.databaseName; + + // Convert the readPreference if its not a write + options.readPreference = resolveReadPreference(options, { db, default: ReadPreference.primary }); + + // Debug information + if (db.s.logger.isDebug()) + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + + // Execute command + db.s.topology.command(`${dbName}.$cmd`, command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Runs a command on the database as admin. + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeDbAdminCommand(db, command, options, callback) { + db.s.topology.command('admin.$cmd', command, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +// Transformation methods for cursor results +function listCollectionsTransforms(databaseName) { + const matching = `${databaseName}.`; + + return { + doc: doc => { + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + }; +} + +/** + * Retrive the current profiling information for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling info. + * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + * @deprecated Query the system.profile collection directly. + */ +function profilingInfo(db, options, callback) { + try { + db + .collection('system.profile') + .find({}, options) + .toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +/** + * Retrieve the current profiling level for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling level. + * @param {Object} [options] Optional settings. See Db.prototype.profilingLevel for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function profilingLevel(db, options, callback) { + executeCommand(db, { profile: -1 }, options, (err, doc) => { + if (err == null && doc.ok === 1) { + const 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); + } + }); +} + +/** + * Remove a user from a database + * + * @method + * @param {Db} db The Db instance on which to remove the user. + * @param {string} username The username. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function removeUser(db, username, options, callback) { + const Db = require('../db'); + + // Attempt to execute command + executeAuthRemoveUserCommand(db, username, options, (err, result) => { + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Locate the user + findOne(collection, { user: username }, finalOptions, (err, user) => { + if (user == null) return handleCallback(callback, err, false); + remove(collection, { user: username }, finalOptions, err => { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +/** + * Set the current profiling level of MongoDB + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings. See Db.prototype.setProfilingLevel for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function setProfilingLevel(db, level, options, callback) { + const command = {}; + let 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; + + executeCommand(db, command, options, (err, doc) => { + if (err == null && doc.ok === 1) return callback(null, level); + return err != null + ? callback(err, null) + : callback(new Error('Error with profile command'), null); + }); +} + +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw MongoError.create({ message: 'database name must be a string', driver: true }); + if (databaseName.length === 0) + throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw MongoError.create({ + message: "database names cannot contain the character '" + invalidChars[i] + "'", + driver: true + }); + } +} + +/** + * Create the command object for Db.prototype.createIndex. + * + * @param {Db} db The Db instance on which to create the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @return {Object} The insert command object. + */ +function createCreateIndexCommand(db, name, fieldOrSpec, options) { + const indexParameters = parseIndexOptions(fieldOrSpec); + const fieldHash = indexParameters.fieldHash; + + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + const selector = { + ns: db.databaseName + '.' + name, + key: fieldHash, + name: indexName + }; + + // Ensure we have a correct finalUnique + const finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options === 'boolean' ? {} : options; + + // Add all the options + const keysToOmit = Object.keys(selector); + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + selector[optionName] = options[optionName]; + } + } + + if (selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; + for (let i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +/** + * Create index using the createIndexes command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + const keysToOmit = Object.keys(indexes[0]).concat([ + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' + ]); + + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + indexes[0][optionName] = options[optionName]; + } + } + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result.ok === 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +/** + * Run the createUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to add. + * @param {string} password The password of the user to add. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthCreateUserCommand(db, username, password, options, callback) { + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + // Unpack all options + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Get additional values + const customData = options.customData != null ? options.customData : {}; + let roles = Array.isArray(options.roles) ? options.roles : []; + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + // Build the command to execute + let command = { + createUser: username, + customData: customData, + roles: roles, + digestPassword + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && err.ok === 0 && err.code === undefined) + return handleCallback(callback, { code: -5000 }, null); + if (err) return handleCallback(callback, err, null); + handleCallback( + callback, + !result.ok ? toError(result) : null, + result.ok ? [{ user: username, pwd: '' }] : null + ); + }); +} + +/** + * Run the dropUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to remove. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthRemoveUserCommand(db, username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + let command = { + dropUser: username + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +module.exports = { + addUser, + collections, + createCollection, + createListener, + createIndex, + dropCollection, + dropDatabase, + ensureIndex, + evaluate, + executeCommand, + executeDbAdminCommand, + listCollectionsTransforms, + indexInformation, + profilingInfo, + profilingLevel, + removeUser, + setProfilingLevel, + validateDatabaseName +}; diff --git a/node_modules/mongodb/lib/operations/mongo_client_ops.js b/node_modules/mongodb/lib/operations/mongo_client_ops.js new file mode 100644 index 0000000..07abd31 --- /dev/null +++ b/node_modules/mongodb/lib/operations/mongo_client_ops.js @@ -0,0 +1,642 @@ +'use strict'; + +const authenticate = require('../authenticate'); +const deprecate = require('util').deprecate; +const Logger = require('mongodb-core').Logger; +const MongoError = require('mongodb-core').MongoError; +const Mongos = require('../topologies/mongos'); +const parse = require('mongodb-core').parseConnectionString; +const ReadPreference = require('mongodb-core').ReadPreference; +const ReplSet = require('../topologies/replset'); +const Server = require('../topologies/server'); +const ServerSessionPool = require('mongodb-core').Sessions.ServerSessionPool; + +const monitoringEvents = [ + 'timeout', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]; +const ignoreOptionNames = ['native_parser']; +const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; +const legacyParse = deprecate( + require('../url_parser'), + 'current URL string parser is deprecated, and will be removed in a future version. ' + + 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' +); +const validOptionNames = [ + 'poolSize', + 'ssl', + 'sslValidate', + 'sslCA', + 'sslCert', + 'sslKey', + 'sslPass', + 'sslCRL', + 'autoReconnect', + 'noDelay', + 'keepAlive', + 'keepAliveInitialDelay', + 'connectTimeoutMS', + 'family', + 'socketTimeoutMS', + 'reconnectTries', + 'reconnectInterval', + 'ha', + 'haInterval', + 'replicaSet', + 'secondaryAcceptableLatencyMS', + 'acceptableLatencyMS', + 'connectWithNoPrimary', + 'authSource', + 'w', + 'wtimeout', + 'j', + 'forceServerObjectId', + 'serializeFunctions', + 'ignoreUndefined', + 'raw', + 'bufferMaxEntries', + 'readPreference', + 'pkFactory', + 'promiseLibrary', + 'readConcern', + 'maxStalenessSeconds', + 'loggerLevel', + 'logger', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs', + 'domainsEnabled', + 'checkServerIdentity', + 'validateOptions', + 'appname', + 'auth', + 'user', + 'password', + 'authMechanism', + 'compression', + 'fsync', + 'readPreferenceTags', + 'numberOfRetries', + 'auto_reconnect', + 'minSize', + 'monitorCommands', + 'retryWrites', + 'useNewUrlParser' +]; + +function addListeners(mongoClient, topology) { + topology.on('authenticated', createListener(mongoClient, 'authenticated')); + topology.on('error', createListener(mongoClient, 'error')); + topology.on('timeout', createListener(mongoClient, 'timeout')); + topology.on('close', createListener(mongoClient, 'close')); + topology.on('parseError', createListener(mongoClient, 'parseError')); + topology.once('open', createListener(mongoClient, 'open')); + topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); + topology.once('all', createListener(mongoClient, 'all')); + topology.on('reconnect', createListener(mongoClient, 'reconnect')); +} + +function assignTopology(client, topology) { + client.topology = topology; + topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); +} + +// Clear out all events +function clearAllEvents(topology) { + monitoringEvents.forEach(event => topology.removeAllListeners(event)); +} + +// Collect all events in order from SDAM +function collectEvents(mongoClient, topology) { + const MongoClient = require('../mongo_client'); + const collectedEvents = []; + + if (mongoClient instanceof MongoClient) { + monitoringEvents.forEach(event => { + topology.on(event, (object1, object2) => { + if (event === 'open') { + collectedEvents.push({ event: event, object1: mongoClient }); + } else { + collectedEvents.push({ event: event, object1: object1, object2: object2 }); + } + }); + }); + } + + return collectedEvents; +} + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance with which to connect. + * @param {string} url The connection URI string + * @param {object} [options] Optional settings. See MongoClient.prototype.connect for a list of options. + * @param {MongoClient~connectCallback} [callback] The command result callback + */ +function connect(mongoClient, url, options, callback) { + options = Object.assign({}, options); + + // If callback is null throw an exception + if (callback == null) { + throw new Error('no callback function provided'); + } + + // Get a logger for MongoClient + const logger = Logger('MongoClient', options); + + // Did we pass in a Server/ReplSet/Mongos + if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { + return connectWithUrl(mongoClient, url, options, connectCallback); + } + + const parseFn = options.useNewUrlParser ? parse : legacyParse; + const transform = options.useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; + + parseFn(url, options, (err, _object) => { + // Do not attempt to connect if parsing error + if (err) return callback(err); + + // Flatten + const object = transform(_object); + + // Parse the string + const _finalOptions = createUnifiedOptions(object, options); + + // Check if we have connection and socket timeout set + if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; + if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; + + if (_finalOptions.db_options && _finalOptions.db_options.auth) { + delete _finalOptions.db_options.auth; + } + + // Store the merged options object + mongoClient.s.options = _finalOptions; + + // Failure modes + if (object.servers.length === 0) { + return callback(new Error('connection string must contain at least one seed host')); + } + + // Do we have a replicaset then skip discovery and go straight to connectivity + if (_finalOptions.replicaSet || _finalOptions.rs_name) { + return createTopology( + mongoClient, + 'replicaset', + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } else if (object.servers.length > 1) { + return createTopology( + mongoClient, + 'mongos', + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } else { + return createServer( + mongoClient, + _finalOptions, + connectHandler(mongoClient, _finalOptions, connectCallback) + ); + } + }); + function connectCallback(err, topology) { + const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError(warningMessage)); + } + + // Return the error and db instance + callback(err, topology); + } +} + +function connectHandler(client, options, callback) { + return (err, topology) => { + if (err) { + return handleConnectCallback(err, topology, callback); + } + + // No authentication just reconnect + if (!options.auth) { + return handleConnectCallback(err, topology, callback); + } + + // Authenticate + authenticate(client, options.user, options.password, options, (err, success) => { + if (success) { + handleConnectCallback(null, topology, callback); + } else { + if (topology) topology.close(); + const authError = err ? err : new Error('Could not authenticate user ' + options.auth[0]); + handleConnectCallback(authError, topology, callback); + } + }); + }; +} + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance with which to connect. + * @param {MongoClient~connectCallback} [callback] The command result callback + */ +function connectOp(mongoClient, err, callback) { + // Did we have a validation error + if (err) return callback(err); + // Fallback to callback based connect + connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { + if (err) return callback(err); + callback(null, mongoClient); + }); +} + +function connectWithUrl(mongoClient, url, options, connectCallback) { + // Set the topology + assignTopology(mongoClient, url); + + // Add listeners + addListeners(mongoClient, url); + + // Propagate the events to the client + relayEvents(mongoClient, url); + + let finalOptions = Object.assign({}, options); + + // If we have a readPreference passed in by the db options, convert it from a string + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + finalOptions.readPreference = new ReadPreference( + options.readPreference || options.read_preference + ); + } + + // Connect + return url.connect( + finalOptions, + connectHandler(mongoClient, finalOptions, (err, topology) => { + if (err) return connectCallback(err, topology); + if (finalOptions.user || finalOptions.password || finalOptions.authMechanism) { + return authenticate( + mongoClient, + finalOptions.user, + finalOptions.password, + finalOptions, + err => { + if (err) return connectCallback(err, topology); + connectCallback(err, topology); + } + ); + } + + connectCallback(err, topology); + }) + ); +} + +function createListener(mongoClient, event) { + const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); + return (v1, v2) => { + if (eventSet.has(event)) { + return mongoClient.emit(event, mongoClient); + } + + mongoClient.emit(event, v1, v2); + }; +} + +function createServer(mongoClient, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + // Set default options + const servers = translateOptions(options); + + const server = servers[0]; + + // Propagate the events to the client + const collectedEvents = collectEvents(mongoClient, server); + + // Connect to topology + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } + // Clear out all the collected event listeners + clearAllEvents(server); + + // Relay all the events + relayEvents(mongoClient, server); + // Add listeners + addListeners(mongoClient, server); + // Check if we are really speaking to a mongos + const ismaster = topology.lastIsMaster(); + + // Set the topology + assignTopology(mongoClient, topology); + + // Do we actually have a mongos + if (ismaster && ismaster.msg === 'isdbgrid') { + // Destroy the current connection + topology.close(); + // Create mongos connection instead + return createTopology(mongoClient, 'mongos', options, callback); + } + + // Fire all the events + replayEvents(mongoClient, collectedEvents); + // Otherwise callback + callback(err, topology); + }); +} + +function createTopology(mongoClient, topologyType, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + const translationOptions = {}; + if (topologyType === 'unified') translationOptions.createServers = false; + + // Set default options + const servers = translateOptions(options, translationOptions); + + // Create the topology + let topology; + if (topologyType === 'mongos') { + topology = new Mongos(servers, options); + } else if (topologyType === 'replicaset') { + topology = new ReplSet(servers, options); + } + + // Add listeners + addListeners(mongoClient, topology); + + // Propagate the events to the client + relayEvents(mongoClient, topology); + + // Open the connection + topology.connect(options, (err, newTopology) => { + if (err) { + topology.close(true); + return callback(err); + } + + assignTopology(mongoClient, newTopology); + callback(null, newTopology); + }); +} + +function createUnifiedOptions(finalOptions, options) { + const childOptions = [ + 'mongos', + 'server', + 'db', + 'replset', + 'db_options', + 'server_options', + 'rs_options', + 'mongos_options' + ]; + const noMerge = ['readconcern', 'compression']; + + for (const name in options) { + if (noMerge.indexOf(name.toLowerCase()) !== -1) { + finalOptions[name] = options[name]; + } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if ( + options[name] && + typeof options[name] === 'object' && + !Buffer.isBuffer(options[name]) && + !Array.isArray(options[name]) + ) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function handleConnectCallback(err, topology, callback) { + return process.nextTick(() => { + try { + callback(err, topology); + } catch (err) { + if (topology) topology.close(); + throw err; + } + }); +} + +function legacyTransformUrlOptions(object) { + return mergeOptions(createUnifiedOptions({}, object), object, false); +} + +/** + * Logout user from server, fire off on all connections and remove all auth info. + * + * @method + * @param {MongoClient} mongoClient The MongoClient instance on which to logout. + * @param {object} [options] Optional settings. See MongoClient.prototype.logout for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function logout(mongoClient, dbName, callback) { + mongoClient.topology.logout(dbName, err => { + if (err) return callback(err); + callback(null, true); + }); +} + +function mergeOptions(target, source, flatten) { + for (const name in source) { + if (source[name] && typeof source[name] === 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +function relayEvents(mongoClient, topology) { + const serverOrCommandEvents = [ + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + + serverOrCommandEvents.forEach(event => { + topology.on(event, (object1, object2) => { + mongoClient.emit(event, object1, object2); + }); + }); +} + +// +// Replay any events due to single server connection switching to Mongos +// +function replayEvents(mongoClient, events) { + for (let i = 0; i < events.length; i++) { + mongoClient.emit(events[i].event, events[i].object1, events[i].object2); + } +} + +const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { + obj[name.toLowerCase()] = name; + return obj; +}, {}); + +function transformUrlOptions(_object) { + let object = Object.assign({ servers: _object.hosts }, _object.options); + for (let name in object) { + const camelCaseName = LEGACY_OPTIONS_MAP[name]; + if (camelCaseName) { + object[camelCaseName] = object[name]; + } + } + if (_object.auth) { + const auth = _object.auth; + for (let i in auth) { + if (auth[i]) { + object[i] = auth[i]; + } + } + + if (auth.username) { + object.auth = auth; + object.user = auth.username; + } + } + + if (_object.defaultDatabase) { + object.dbName = _object.defaultDatabase; + } + + if (object.maxpoolsize) { + object.poolSize = object.maxpoolsize; + } + + if (object.readconcernlevel) { + object.readConcern = { level: object.readconcernlevel }; + } + + if (object.wtimeoutms) { + object.wtimeout = object.wtimeoutms; + } + + return object; +} + +function translateOptions(options, translationOptions) { + translationOptions = Object.assign({}, { createServers: true }, translationOptions); + + // If we have a readPreference passed in by the db options + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if (options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; + if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; + + if (!translationOptions.createServers) { + return; + } + + // Create server instances + return options.servers.map(serverObj => { + return serverObj.domain_socket + ? new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +// Validate options object +function validOptions(options) { + const _validOptions = validOptionNames.concat(legacyOptionNames); + + for (const name in options) { + if (ignoreOptionNames.indexOf(name) !== -1) { + continue; + } + + if (_validOptions.indexOf(name) === -1 && options.validateOptions) { + return new MongoError(`option ${name} is not supported`); + } else if (_validOptions.indexOf(name) === -1) { + console.warn(`the options [${name}] is not supported`); + } + + if (legacyOptionNames.indexOf(name) !== -1) { + console.warn( + `the server/replset/mongos/db options are deprecated, ` + + `all their options are supported at the top level of the options object [${validOptionNames}]` + ); + } + } +} + +module.exports = { connectOp, logout, validOptions }; diff --git a/node_modules/mongodb/lib/topologies/mongos.js b/node_modules/mongodb/lib/topologies/mongos.js new file mode 100644 index 0000000..dc14277 --- /dev/null +++ b/node_modules/mongodb/lib/topologies/mongos.js @@ -0,0 +1,452 @@ +'use strict'; + +const TopologyBase = require('./topology_base').TopologyBase; +const MongoError = require('mongodb-core').MongoError; +const CMongos = require('mongodb-core').Mongos; +const Cursor = require('../cursor'); +const Server = require('./server'); +const Store = require('./topology_base').Store; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey] 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) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @fires Mongos#commandStarted + * @fires Mongos#commandSucceeded + * @fires Mongos#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +class Mongos extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Internal state + this.s = { + // Create the Mongos + coreTopology: new CMongos(seedlist, clonedOptions), + // Server capabilities + sCapabilities: null, + // Debug turned on + debug: clonedOptions.debug, + // Store option defaults + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Actual store of callbacks + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Force close the topology + self.close(true); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + var events = ['timeout', 'error', 'close', 'fullsetup']; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.on('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + + // Set up serverConfig listeners + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + // Join and leave events + self.s.coreTopology.on('joined', relay('joined')); + self.s.coreTopology.on('left', relay('left')); + + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/node_modules/mongodb/lib/topologies/replset.js b/node_modules/mongodb/lib/topologies/replset.js new file mode 100644 index 0000000..0a73134 --- /dev/null +++ b/node_modules/mongodb/lib/topologies/replset.js @@ -0,0 +1,497 @@ +'use strict'; + +const Server = require('./server'); +const Cursor = require('../cursor'); +const MongoError = require('mongodb-core').MongoError; +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const CReplSet = require('mongodb-core').ReplSet; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'replicaSet', + 'rs_name', + 'secondaryAcceptableLatencyMS', + 'connectWithNoPrimary', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslCRL', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'strategy', + 'debug', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'maxStalenessSeconds', + 'promiseLibrary', + 'minSize', + 'monitorCommands' +]; + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] 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) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @fires ReplSet#commandStarted + * @fires ReplSet#commandSucceeded + * @fires ReplSet#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +class ReplSet extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the ReplSet + var coreTopology = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + coreTopology.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + coreTopology: coreTopology, + // Server capabilities + sCapabilities: null, + // Debug tag + tag: options.tag, + // Store options + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Store + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + + // Debug + if (clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable: true, + get: function() { + return coreTopology; + } + }); + } + } + + // Connect method + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + }; + }; + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if (t === 'start') { + self.emit('ha_connect', t, state); + } else if (t === 'end') { + self.emit('ha_ismaster', t, state); + } + }; + + // Set up serverConfig listeners + self.s.coreTopology.on('joined', replsetRelay('joined')); + self.s.coreTopology.on('left', relay('left')); + self.s.coreTopology.on('ping', relay('ping')); + self.s.coreTopology.on('ha', relayHa); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self, self); + }); + + self.s.coreTopology.on('all', function() { + self.emit('all', null, self); + }); + + // Connect handler + var connectHandler = function() { + // Set up listeners + self.s.coreTopology.once('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.once('close', errorHandler('close')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.coreTopology.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.coreTopology.destroy(); + + // Try to callback + try { + callback(err); + } catch (err) { + if (!self.s.coreTopology.isConnected()) + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } + + close(forceClosed) { + super.close(forceClosed); + + ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); + } +} + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/node_modules/mongodb/lib/topologies/server.js b/node_modules/mongodb/lib/topologies/server.js new file mode 100644 index 0000000..77d8b6e --- /dev/null +++ b/node_modules/mongodb/lib/topologies/server.js @@ -0,0 +1,455 @@ +'use strict'; + +const CServer = require('mongodb-core').Server; +const Cursor = require('../cursor'); +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const MongoError = require('mongodb-core').MongoError; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'reconnectInterval', + 'monitoring', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'compression', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] 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) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#commandStarted + * @fires Server#commandSucceeded + * @fires Server#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +class Server extends TopologyBase { + constructor(host, port, options) { + super(); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Promise library + const promiseLibrary = options.promiseLibrary; + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if (host.indexOf('/') !== -1) { + if (port != null && typeof port === 'object') { + options = port; + port = null; + } + } else if (port == null) { + throw MongoError.create({ message: 'port must be specified', driver: true }); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + host: host, + port: port, + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the mongodb-core ones + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + coreTopology: new CServer(clonedOptions), + // Server capabilities + sCapabilities: null, + // Cloned options + clonedOptions: clonedOptions, + // Reconnect + reconnect: clonedOptions.reconnect, + // Emit error + emitError: clonedOptions.emitError, + // Pool size + poolSize: clonedOptions.size, + // Store Options + storeOptions: storeOptions, + // Store + store: store, + // Host + host: host, + // Port + port: port, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: [], + // Promise library + promiseLibrary: promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = this.s.clonedOptions; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.coreTopology.removeListener(e, connectHandlers[e]); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + }; + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + }; + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + // Only called on destroy + self.s.coreTopology.on('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Clear out all the current handlers left over + [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Add the event handlers + self.s.coreTopology.once('timeout', connectHandlers.timeout); + self.s.coreTopology.once('error', connectHandlers.error); + self.s.coreTopology.once('close', connectHandlers.close); + self.s.coreTopology.once('connect', connectHandler); + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); + self.s.coreTopology.on('monitoring', relay('monitoring')); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable: true, + get: function() { + return this.s.coreTopology.connections().length; + } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable: true, + get: function() { + return this.s.reconnect; + } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable: true, + get: function() { + return this.s.host; + } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable: true, + get: function() { + return this.s.port; + } +}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Server#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Server#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Server#commandFailed + * @type {object} + */ + +module.exports = Server; diff --git a/node_modules/mongodb/lib/topologies/topology_base.js b/node_modules/mongodb/lib/topologies/topology_base.js new file mode 100644 index 0000000..54f848c --- /dev/null +++ b/node_modules/mongodb/lib/topologies/topology_base.js @@ -0,0 +1,446 @@ +'use strict'; + +const EventEmitter = require('events'), + MongoError = require('mongodb-core').MongoError, + f = require('util').format, + os = require('os'), + translateReadPreference = require('../utils').translateReadPreference, + ClientSession = require('mongodb-core').Sessions.ClientSession; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + + // Internal state + this.s = { + storedOps: storedOps, + storeOptions: storeOptions, + topology: topology + }; + + Object.defineProperty(this, 'length', { + enumerable: true, + get: function() { + return self.s.storedOps.length; + } + }); +}; + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); +}; + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); +}; + +Store.prototype.flush = function(err) { + while (this.s.storedOps.length > 0) { + this.s.storedOps + .shift() + .c( + err || + MongoError.create({ message: f('no connection available for operation'), driver: true }) + ); + } +}; + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; + var executeSecondary = + typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; + + // Execute all the stored ops + while (ops.length > 0) { + var op = ops.shift(); + + if (op.t === 'cursor') { + if (executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if ( + executePrimary && + op.o.options && + op.o.options.readPreference && + primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } else if ( + !executePrimary && + executeSecondary && + op.o.options && + op.o.options.readPreference && + secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } + } else if (op.t === 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if (executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + executePrimary && + op.op && + op.op.readPreference && + primaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + !executePrimary && + executeSecondary && + op.op && + op.op.readPreference && + secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +}; + +Store.prototype.all = function() { + return this.s.storedOps; +}; + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + get: function() { + return value; + } + }); + }; + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if (ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if (ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if (ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if (ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if (ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if (ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if (ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, 'hasAggregationCursor', aggregationCursor); + setup_get_property(this, 'hasWriteCommands', writeCommands); + setup_get_property(this, 'hasTextSearch', textSearch); + setup_get_property(this, 'hasAuthCommands', authCommands); + setup_get_property(this, 'hasListCollectionsCommand', listCollections); + setup_get_property(this, 'hasListIndexesCommand', listIndexes); + setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); + setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); + setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); + setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); + setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); +}; + +// Get package.json variable +const driverVersion = require('../../package.json').version, + nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), + type = os.type(), + name = process.platform, + architecture = process.arch, + release = os.release(); + +class TopologyBase extends EventEmitter { + constructor() { + super(); + + // Build default client information + this.clientInfo = { + driver: { + name: 'nodejs', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + }; + + this.setMaxListeners(Infinity); + } + + // Sessions related methods + hasSessionSupport() { + return this.logicalSessionTimeoutMinutes != null; + } + + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions = this.s.sessions.filter(s => !s.equals(session)); + }); + + this.s.sessions.push(session); + return session; + } + + endSessions(sessions, callback) { + return this.s.coreTopology.endSessions(sessions, callback); + } + + // Server capabilities + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.s.coreTopology.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + this.s.coreTopology.command(ns, cmd, translateReadPreference(options), callback); + } + + // Insert + insert(ns, ops, options, callback) { + this.s.coreTopology.insert(ns, ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + this.s.coreTopology.update(ns, ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + this.s.coreTopology.remove(ns, ops, options, callback); + } + + // IsConnected + isConnected(options) { + options = options || {}; + options = translateReadPreference(options); + + return this.s.coreTopology.isConnected(options); + } + + // IsDestroyed + isDestroyed() { + return this.s.coreTopology.isDestroyed(); + } + + // Cursor + cursor(ns, cmd, options) { + options = options || {}; + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + options.topology = this; + + return this.s.coreTopology.cursor(ns, cmd, options); + } + + lastIsMaster() { + return this.s.coreTopology.lastIsMaster(); + } + + selectServer(selector, options, callback) { + return this.s.coreTopology.selectServer(selector, options, callback); + } + + /** + * Unref all sockets + * @method + */ + unref() { + return this.s.coreTopology.unref(); + } + + auth() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.coreTopology.auth.apply(this.s.coreTopology, args); + } + + logout() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.coreTopology.logout.apply(this.s.coreTopology, args); + } + + /** + * All raw connections + * @method + * @return {array} + */ + connections() { + return this.s.coreTopology.connections(); + } + + close(forceClosed) { + // If we have sessions, we want to individually move them to the session pool, + // and then send a single endSessions call. + if (this.s.sessions.length) { + this.s.sessions.forEach(session => session.endSession()); + } + + if (this.s.sessionPool) { + this.s.sessionPool.endAllPooledSessions(); + } + + this.s.coreTopology.destroy({ + force: typeof forceClosed === 'boolean' ? forceClosed : false + }); + + // We need to wash out all stored processes + if (forceClosed === true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + } +} + +// Properties +Object.defineProperty(TopologyBase.prototype, 'bson', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.bson; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'parserType', { + enumerable: true, + get: function() { + return this.s.coreTopology.parserType; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.coreTopology.logicalSessionTimeoutMinutes; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'type', { + enumerable: true, + get: function() { + return this.s.coreTopology.type; + } +}); + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; +exports.TopologyBase = TopologyBase; diff --git a/node_modules/mongodb/lib/url_parser.js b/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..7cc0b2f --- /dev/null +++ b/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,622 @@ +'use strict'; + +const ReadPreference = require('mongodb-core').ReadPreference, + parser = require('url'), + f = require('util').format, + Logger = require('mongodb-core').Logger, + dns = require('dns'); + +module.exports = function(url, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + let result; + try { + result = parser.parse(url, true); + } catch (e) { + return callback(new Error('URL malformed, cannot be parsed')); + } + + if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { + return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); + } + + if (result.protocol === 'mongodb:') { + return parseHandler(url, options, callback); + } + + // Otherwise parse this as an SRV record + if (result.hostname.split('.').length < 3) { + return callback(new Error('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + + if (result.pathname && result.pathname.match(',')) { + return callback(new Error('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, function(err, addresses) { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new Error('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback(new Error('Server record does not share hostname with parent URI')); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map(function(address, i) { + if (i === 0) return `${base}${address.name}:${address.port}`; + else return `${address.name}:${address.port}`; + }); + + let connectionString = connectionStrings.join(',') + '/'; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && !result.search) { + connectionStringOptions.push('ssl=true'); + } else if (!options.ssl && result.search && !result.search.match('ssl')) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, function(err, record) { + if (err && err.code !== 'ENODATA') return callback(err); + if (err && err.code === 'ENODATA') record = null; + + if (record) { + if (record.length > 1) { + return callback(new Error('Multiple text records not allowed')); + } + + record = record[0]; + if (record.length > 1) record = record.join(''); + else record = record[0]; + + if (!record.includes('authSource') && !record.includes('replicaSet')) { + return callback(new Error('Text record must only set `authSource` or `replicaSet`')); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseHandler(connectionString, options, callback); + }); + }); +}; + +function matchesParentDomain(srvAddress, parentDomain) { + let regex = /^.*?\./; + let srv = `.${srvAddress.replace(regex, '')}`; + let parent = `.${parentDomain.replace(regex, '')}`; + if (srv.endsWith(parent)) return true; + else return false; +} + +function parseHandler(address, options, callback) { + let result, err; + try { + result = parseConnectionString(address, options); + } catch (e) { + err = e; + } + + return err ? callback(err, null) : callback(null, result); +} + +function parseConnectionString(url, options) { + // Variables + let connection_part = ''; + let auth_part = ''; + let query_string_part = ''; + let dbName = 'admin'; + + // Url parser result + let result = parser.parse(url, true); + if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { + throw new Error('No hostname or hostnames provided in connection string'); + } + + if (result.port === '0') { + throw new Error('Invalid port (zero) with hostname'); + } + + if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('Invalid port (larger than 65535) with hostname'); + } + + if ( + result.path && + result.path.length > 0 && + result.path[0] !== '/' && + url.indexOf('.sock') === -1 + ) { + throw new Error('Missing delimiting slash between hosts and options'); + } + + if (result.query) { + for (let name in result.query) { + if (name.indexOf('::') !== -1) { + throw new Error('Double colon in host identifier'); + } + + if (result.query[name] === '') { + throw new Error('Query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if (result.auth) { + let parts = result.auth.split(':'); + if (url.indexOf(result.auth) !== -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + let clean = url.split('?').shift(); + + // Extract the list of hosts + let strings = clean.split(','); + let hosts = []; + + for (let i = 0; i < strings.length; i++) { + let hostString = strings[i]; + + if (hostString.indexOf('mongodb') !== -1) { + if (hostString.indexOf('@') !== -1) { + hosts.push(hostString.split('@').pop()); + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if (hostString.indexOf('/') !== -1) { + hosts.push(hostString.split('/').shift()); + } else if (hostString.indexOf('/') === -1) { + hosts.push(hostString.trim()); + } + } + + for (let i = 0; i < hosts.length; i++) { + let r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if (r.path && r.path.indexOf('.sock') !== -1) continue; + if (r.path && r.path.indexOf(':') !== -1) { + // Not connecting to a socket so check for an extra slash in the hostname. + // Using String#split as perf is better than match. + if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { + throw new Error('Slash in host identifier'); + } else { + throw new Error('Double colon in host identifier'); + } + } + } + + // 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 there is not more than one unescaped slash + if (connection_part.split('/').length > 2) { + throw new Error( + "Unsupported host '" + + connection_part.split('?')[0] + + "', hosts must be URL encoded and contain at most one unencoded slash" + ); + } + + // 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]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf('/') !== -1) { + if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split( + '/', + connection_part.indexOf('.sock') + '.sock'.length + ); + } + } else if (connection_part.indexOf('/') !== -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split('/').length > 2) { + if (connection_part.split('/')[2].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split('/')[1]; + connection_part = connection_part.split('/')[0]; + } + + // URI decode the host information + connection_part = decodeURIComponent(connection_part); + + // Result object + let object = {}; + + // Pick apart the authentication part of the string + let authPart = auth_part || ''; + let auth = authPart.split(':', 2); + + // Decode the authentication URI components and verify integrity + let user = decodeURIComponent(auth[0]); + if (auth[0] !== encodeURIComponent(user)) { + throw new Error('Username contains an illegal unescaped character'); + } + auth[0] = user; + + if (auth[1]) { + let pass = decodeURIComponent(auth[1]); + if (auth[1] !== encodeURIComponent(pass)) { + throw new Error('Password contains an illegal unescaped character'); + } + auth[1] = pass; + } + + // Add auth to final object if we have 2 elements + if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; + // if user provided auth options, use that + if (options && options.auth != null) object.auth = options.auth; + + // Variables used for temporary storage + let hostPart; + let urlOptions; + let servers; + let compression; + let serverOptions = { socketOptions: {} }; + let dbOptions = { read_preference_tags: [] }; + let replSetServersOptions = { socketOptions: {} }; + let mongosOptions = { socketOptions: {} }; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if (url.match(/\.sock/)) { + // Split out the socket part + let 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]; + domainSocket = decodeURIComponent(domainSocket); + servers = [{ domain_socket: domainSocket }]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + let deduplicatedServers = {}; + + // Parse all server results + servers = hostPart + .split(',') + .map(function(h) { + let _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + let hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate servr + if (deduplicatedServers[_host + '_' + _port]) return null; + deduplicatedServers[_host + '_' + _port] = 1; + + // Return the mapped object + return { host: _host, port: _port }; + }) + .filter(function(x) { + return x != null; + }); + } + + // 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'; + dbOptions.slaveOk = value === 'true'; + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = value === 'true'; + break; + case 'ssl': + if (value === 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = value === 'true'; + replSetServersOptions.ssl = value === 'true'; + mongosOptions.ssl = value === 'true'; + break; + case 'sslValidate': + serverOptions.sslValidate = value === 'true'; + replSetServersOptions.sslValidate = value === 'true'; + mongosOptions.sslValidate = 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.j = value === 'true'; + break; + case 'safe': + dbOptions.safe = value === 'true'; + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = value === 'true'; + break; + case 'readConcernLevel': + dbOptions.readConcern = { level: value }; + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if (isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if (value === 'GSSAPI') { + // If no password provided decode only the principal + if (object.auth == null) { + let urlDecodeAuthPart = decodeURIComponent(authPart); + if (urlDecodeAuthPart.indexOf('@') === -1) + throw new Error('GSSAPI requires a provided principal'); + object.auth = { user: urlDecodeAuthPart, password: null }; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if (value === 'MONGODB-X509') { + object.auth = { user: decodeURIComponent(authPart) }; + } + + // Only support GSSAPI or MONGODB-CR for now + if ( + value !== 'GSSAPI' && + value !== 'MONGODB-X509' && + value !== 'MONGODB-CR' && + value !== 'DEFAULT' && + value !== 'SCRAM-SHA-1' && + value !== 'SCRAM-SHA-256' && + value !== 'PLAIN' + ) + throw new Error( + 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' + ); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + { + // Split up into key, value pairs + let values = value.split(','); + let o = {}; + // For each value split into key, value + values.forEach(function(x) { + let v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if (typeof o.CANONICALIZE_HOST_NAME === 'string') + dbOptions.gssapiCanonicalizeHostName = + o.CANONICALIZE_HOST_NAME === 'true' ? true : false; + } + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if (!ReadPreference.isValid(value)) + throw new Error( + 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' + ); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + { + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + let tagObject = {}; + if (value == null || value === '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + let tags = value.split(/,/); + for (let i = 0; i < tags.length; i++) { + let parts = tags[i].trim().split(/:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + } + break; + case 'compressors': + { + compression = serverOptions.compression || {}; + let compressors = value.split(','); + if ( + !compressors.every(function(compressor) { + return compressor === 'snappy' || compressor === 'zlib'; + }) + ) { + throw new Error('Compressors must be at least one of snappy or zlib'); + } + + compression.compressors = compressors; + serverOptions.compression = compression; + } + break; + case 'zlibCompressionLevel': + { + compression = serverOptions.compression || {}; + let zlibCompressionLevel = parseInt(value, 10); + if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { + throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); + } + + compression.zlibCompressionLevel = zlibCompressionLevel; + serverOptions.compression = compression; + } + break; + case 'retryWrites': + dbOptions.retryWrites = value === 'true'; + break; + case 'minSize': + dbOptions.minSize = parseInt(value, 10); + break; + default: + { + let logger = Logger('URL Parser'); + logger.warn(`${name} is not supported as a connection string option`); + } + 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.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // make sure that user-provided options are applied with priority + dbOptions = Object.assign(dbOptions, options); + + // Add servers to result + object.servers = servers; + + // Returned parsed object + return object; +} diff --git a/node_modules/mongodb/lib/utils.js b/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..a96f584 --- /dev/null +++ b/node_modules/mongodb/lib/utils.js @@ -0,0 +1,720 @@ +'use strict'; + +const MongoError = require('mongodb-core').MongoError; +const ReadPreference = require('mongodb-core').ReadPreference; + +var shallowClone = function(obj) { + var copy = {}; + for (var name in obj) copy[name] = obj[name]; + return copy; +}; + +// Figure out the read preference +var translateReadPreference = function(options) { + var r = null; + if (options.readPreference) { + r = options.readPreference; + } else { + return options; + } + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +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 (sortValue == null) return null; + if (Array.isArray(sortValue)) { + if (sortValue.length === 0) { + return null; + } + + 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 (sortValue != null && typeof sortValue === 'object') { + orderBy = sortValue; + } else if (typeof sortValue === 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return orderBy; +}); + +var checkCollectionName = function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new MongoError('collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoError('collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + throw new MongoError("collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + throw new MongoError("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if (collectionName.indexOf('\x00') !== -1) { + throw new MongoError('collection names cannot contain a null character'); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if (callback == null) return; + + if (callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch (err) { + process.nextTick(function() { + throw err; + }); + return false; + } + + return true; +}; + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({ message: msg, driver: true }); + + // Get all object keys + var keys = typeof error === 'object' ? Object.keys(error) : []; + + for (var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch (err) { + // continue + } + } + + return e; +}; + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + 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 (Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (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 (isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +}; + +var isObject = (exports.isObject = function(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +}); + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var decorateCommand = function(command, options, exclude) { + for (var name in options) { + if (exclude.indexOf(name) === -1) command[name] = options[name]; + } + + return command; +}; + +var mergeOptions = function(target, source) { + for (var name in source) { + target[name] = source[name]; + } + + return target; +}; + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + sslCA: 'ca', + sslCRL: 'crl', + sslValidate: 'rejectUnauthorized', + sslKey: 'key', + sslCert: 'cert', + sslPass: 'passphrase', + // SocketTimeout translation options + socketTimeoutMS: 'socketTimeout', + connectTimeoutMS: 'connectionTimeout', + // Replicaset options + replicaSet: 'setName', + rs_name: 'setName', + secondaryAcceptableLatencyMS: 'acceptableLatency', + connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', + // Mongos options + acceptableLatencyMS: 'localThresholdMS' + }; + + for (var name in source) { + if (translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +}; + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for (var name in options) { + if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +}; + +// Write concern keys +var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; + +// Merge the write concern options +var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { + // Mix in any allowed options + for (var i = 0; i < keys.length; i++) { + if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { + targetOptions[keys[i]] = sourceOptions[keys[i]]; + } + } + + // No merging of write concern + if (!mergeWriteConcern) return targetOptions; + + // Found no write Concern options + var found = false; + for (i = 0; i < writeConcernKeys.length; i++) { + if (targetOptions[writeConcernKeys[i]]) { + found = true; + break; + } + } + + if (!found) { + for (i = 0; i < writeConcernKeys.length; i++) { + if (sourceOptions[writeConcernKeys[i]]) { + targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; + } + } + } + + return targetOptions; +}; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {function} operation The operation to execute + * @param {array} args Arguments to apply the provided operation + * @param {object} [options] Options that modify the behavior of the method + * @param {function]} [options.resultMutator] Allows for the result of the operation to be changed for custom return types + */ +const executeOperation = (topology, operation, args, options) => { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!Array.isArray(args)) { + throw new TypeError('This method requires an array of arguments to apply'); + } + + options = options || {}; + const Promise = topology.s.promiseLibrary; + let resultMutator = options.resultMutator; + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, opOptions, owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner && !options.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + if (resultMutator) return resolve(resultMutator(result)); + resolve(result); + }); + } else { + if (err) return reject(err); + if (resultMutator) return resolve(resultMutator(result)); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + throw new TypeError('final argument to `executeOperation` must be a callback'); + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + } + }); +}; + +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * + * @param {object} target The target command to which we will apply retryWrites. + * @param {object} db The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * + * @param {Object} target the target command we will be applying the write concern to + * @param {Object} sources sources where we can inherit default write concerns from + * @param {Object} [options] optional settings passed into a command for write concern overrides + * @returns {Object} the (now) decorated target + */ +function applyWriteConcern(target, sources, options) { + options = options || {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + if (options.w != null || options.j != null || options.fsync != null) { + const writeConcern = {}; + if (options.w != null) writeConcern.w = options.w; + if (options.wtimeout != null) writeConcern.wtimeout = options.wtimeout; + if (options.j != null) writeConcern.j = options.j; + if (options.fsync != null) writeConcern.fsync = options.fsync; + return Object.assign(target, { writeConcern }); + } + + if ( + coll && + (coll.writeConcern.w != null || coll.writeConcern.j != null || coll.writeConcern.fsync != null) + ) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if ( + db && + (db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) + ) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Resolves a read preference based on well-defined inheritance rules. This method will not only + * determine the read preference (if there is one), but will also ensure the returned value is a + * properly constructed instance of `ReadPreference`. + * + * @param {Object} options The options passed into the method, potentially containing a read preference + * @param {Object} sources Sources from which we can inherit a read preference + * @returns {(ReadPreference|null)} The resolved read preference + */ +function resolveReadPreference(options, sources) { + options = options || {}; + sources = sources || {}; + + const db = sources.db; + const coll = sources.collection; + const defaultReadPreference = sources.default; + const session = options.session; + + let readPreference; + if (options.readPreference) { + readPreference = options.readPreference; + } else if (session && session.inTransaction() && session.transaction.options.readPreference) { + // The transaction’s read preference MUST override all other user configurable read preferences. + readPreference = session.transaction.options.readPreference; + } else { + if (coll && coll.s.readPreference) { + readPreference = coll.s.readPreference; + } else if (db && db.s.readPreference) { + readPreference = db.s.readPreference; + } else if (defaultReadPreference) { + readPreference = defaultReadPreference; + } + } + + // do we even have a read preference? + if (readPreference == null) { + return null; + } + + // now attempt to convert the read preference if necessary + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } else if ( + readPreference && + !(readPreference instanceof ReadPreference) && + typeof readPreference === 'object' + ) { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + readPreference = new ReadPreference(mode, readPreference.tags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds + }); + } + } else if (!(readPreference instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return readPreference; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * + * @param {object} [command] the command on which to apply collation + * @param {(Cursor|Collection)} [target] target of command + * @param {object} [options] options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const topology = target.s && target.s.topology; + + if (!topology) { + throw new TypeError('parameter "target" is missing a topology'); + } + + const capabilities = target.s.topology.capabilities(); + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoError(`server ${topology.s.coreTopology.name} does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * + * @param {object} command the command on which to apply the read concern + * @param {Collection} coll the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll) { + let readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); +const emitConsoleWarning = msg => console.error(msg); +const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; + +/** + * Default message handler for generating deprecation warnings. + * + * @param {string} name function name + * @param {string} option option name + * @return {string} warning message + * @ignore + * @api private + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +/** + * Deprecates a given function's options. + * + * @param {object} config configuration for deprecation + * @param {string} config.name function name + * @param {Array} config.deprecatedOptions options to deprecate + * @param {number} config.optionsIndex index of options object in function arguments array + * @param {function} [config.msgHandler] optional custom message handler to generate warnings + * @param {function} fn the target function of deprecation + * @return {function} modified function that warns once per deprecated option, and executes original function + * @ignore + * @api private + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated() { + const options = arguments[config.optionsIndex]; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.apply(this, arguments); + } + + config.deprecatedOptions.forEach(deprecatedOption => { + if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitDeprecationWarning(msg); + if (this && this.getLogger) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + }); + + return fn.apply(this, arguments); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +module.exports = { + filterOptions, + mergeOptions, + translateOptions, + shallowClone, + getSingleProperty, + checkCollectionName, + toError, + formattedOrderClause, + parseIndexOptions, + normalizeHintField, + handleCallback, + decorateCommand, + isObject, + debugOptions, + MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, + mergeOptionsAndWriteConcern, + translateReadPreference, + executeOperation, + applyRetryableWrites, + applyWriteConcern, + resolveReadPreference, + isPromiseLike, + decorateWithCollation, + decorateWithReadConcern, + deprecateOptions +}; diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json index 56fb31e..da6019b 100644 --- a/node_modules/mongodb/package.json +++ b/node_modules/mongodb/package.json @@ -1,255 +1,89 @@ { - "_from": "mongodb@1.4.38", - "_id": "mongodb@1.4.38", + "_from": "mongodb", + "_id": "mongodb@3.1.9", "_inBundle": false, - "_integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "_integrity": "sha512-f+Og32wK/ovzVlC1S6Ft7yjVTvNsAOs6pBpDrPd2/3wPO9ijNsQrTNntuECjOSxGZpPVl0aRqgHzF1e9e+KvnQ==", "_location": "/mongodb", "_phantomChildren": {}, "_requested": { - "type": "version", + "type": "tag", "registry": true, - "raw": "mongodb@1.4.38", + "raw": "mongodb", "name": "mongodb", "escapedName": "mongodb", - "rawSpec": "1.4.38", + "rawSpec": "", "saveSpec": null, - "fetchSpec": "1.4.38" + "fetchSpec": "latest" }, "_requiredBy": [ - "/mongoose" + "#USER", + "/" ], - "_resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", - "_shasum": "8cffd618100af3a4648a995498bfcfcb4ed8abd2", - "_spec": "mongodb@1.4.38", - "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.9.tgz", + "_shasum": "9bd205b36b6ddf4bd1fb6c3c31641e1994b62075", + "_spec": "mongodb", + "_where": "E:\\github\\node-dc-mongo", "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" + "url": "https://github.com/mongodb/node-mongodb-native/issues" }, "bundleDependencies": false, - "config": { - "native": false - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - }, - { - "name": "Gregory Langlais" - }, - { - "name": "Samantha Ritter" - } - ], "dependencies": { - "bson": "~0.2", - "kerberos": "0.0.11", - "readable-stream": "latest" + "mongodb-core": "3.1.8", + "safe-buffer": "^5.1.2" }, - "deprecated": "Please upgrade to 2.2.19 or higher", - "description": "A node.js driver for MongoDB", + "deprecated": false, + "description": "The official MongoDB driver for Node.js", "devDependencies": { - "dox": "0.4.4", - "ejs": "0.6.1", - "gleak": "0.5.0", - "integra": "0.1.8", - "markdown": "0.3.1", - "mongodb-tools": "~1.0", - "mongodb-version-manager": "0.7.0", - "nodeunit": "0.7.3", - "optimist": "latest", - "request": "2.12.0", - "rimraf": "2.2.6", - "semver": "4.1.0", - "uglify-js": "1.2.5" - }, - "directories": { - "lib": "./lib/mongodb" + "bluebird": "3.5.0", + "bson": "^1.0.4", + "chai": "^4.1.1", + "chai-subset": "^1.6.0", + "co": "4.6.0", + "coveralls": "^2.11.6", + "eslint": "^4.5.0", + "eslint-plugin-prettier": "^2.2.0", + "istanbul": "^0.4.5", + "jsdoc": "3.5.5", + "lodash.camelcase": "^4.3.0", + "mocha-sinon": "^2.1.0", + "mongodb-extjson": "^2.1.1", + "mongodb-mock-server": "^1.0.0", + "mongodb-test-runner": "^1.1.18", + "prettier": "~1.12.0", + "semver": "^5.5.0", + "sinon": "^4.3.0", + "sinon-chai": "^3.2.0", + "standard-version": "^4.4.0", + "worker-farm": "^1.5.0" }, "engines": { - "node": ">=0.6.19" + "node": ">=4" }, - "homepage": "http://mongodb.github.com/node-mongodb-native/", + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb/node-mongodb-native", "keywords": [ "mongodb", - "mongo", "driver", - "db" - ], - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } + "official" ], - "main": "./lib/mongodb/index", + "license": "Apache-2.0", + "main": "index.js", "name": "mongodb", - "optionalDependencies": { - "kerberos": "0.0.11", - "readable-stream": "latest" - }, "repository": { "type": "git", "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" }, "scripts": { - "test": "node test/runner.js -t functional" + "bench": "node test/driverBench/", + "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/unit test/functional", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", + "lint": "eslint lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mongodb-test-runner -t 60000 test/unit test/functional" }, - "version": "1.4.38" + "version": "3.1.9" } diff --git a/node_modules/bson/.travis.yml b/node_modules/mongoose/node_modules/bson/.travis.yml similarity index 100% rename from node_modules/bson/.travis.yml rename to node_modules/mongoose/node_modules/bson/.travis.yml diff --git a/node_modules/bson/HISTORY b/node_modules/mongoose/node_modules/bson/HISTORY similarity index 100% rename from node_modules/bson/HISTORY rename to node_modules/mongoose/node_modules/bson/HISTORY diff --git a/node_modules/mongodb/LICENSE b/node_modules/mongoose/node_modules/bson/LICENSE similarity index 100% rename from node_modules/mongodb/LICENSE rename to node_modules/mongoose/node_modules/bson/LICENSE diff --git a/node_modules/bson/Makefile b/node_modules/mongoose/node_modules/bson/Makefile similarity index 100% rename from node_modules/bson/Makefile rename to node_modules/mongoose/node_modules/bson/Makefile diff --git a/node_modules/mongoose/node_modules/bson/README.md b/node_modules/mongoose/node_modules/bson/README.md new file mode 100644 index 0000000..5cac5b9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/README.md @@ -0,0 +1,69 @@ +Javascript + C++ BSON parser +============================ + +This BSON parser is primarily meant to be used with the `mongodb` node.js driver. +However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. +The current build is located in the `browser_build/bson.js` file. + +A simple example of how to use BSON in the browser: + +```html + + + + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = bson.BSONPure.BSON; +var Long = bson.BSONPure.Long; + +var doc = {long: Long.fromNumber(100)} + +// Serialize a document +var data = BSON.serialize(doc, false, true, false); +console.log("data:", data); + +// Deserialize the resulting Buffer +var doc_2 = BSON.deserialize(data); +console.log("doc_2:", doc_2); +``` + +The API consists of two simple methods to serialize/deserialize objects to/from BSON format: + + * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** + * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports + + * BSON.deserialize(buffer, options, isArray) + * Options + * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * @param {TypedArray/Array} a TypedArray/Array containing the BSON data + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/bson/binding.gyp b/node_modules/mongoose/node_modules/bson/binding.gyp similarity index 100% rename from node_modules/bson/binding.gyp rename to node_modules/mongoose/node_modules/bson/binding.gyp diff --git a/node_modules/mongoose/node_modules/bson/browser_build/bson.js b/node_modules/mongoose/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->0){ + id = pkg.modules[i].id; + + if(id==moduleId || id == moduleIndexId){ + module = pkg.modules[i]; + break; + } + } + + return module; +} + +function newRequire(callingModule){ + function require(uri){ + var module, pkg; + + if(/^\./.test(uri)){ + module = findModule(callingModule, uri); + } else if ( ties && ties.hasOwnProperty( uri ) ) { + return ties[uri]; + } else if ( aliases && aliases.hasOwnProperty( uri ) ) { + return require(aliases[uri]); + } else { + pkg = pkgmap[uri]; + + if(!pkg && nativeRequire){ + try { + pkg = nativeRequire(uri); + } catch (nativeRequireError) {} + + if(pkg) return pkg; + } + + if(!pkg){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module = pkg.index; + } + + if(!module){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module.parent = callingModule; + return module.call(); + }; + + + return require; +} + + +function module(parent, id, wrapper){ + var mod = { pkg: parent, id: id, wrapper: wrapper }, + cached = false; + + mod.exports = {}; + mod.require = newRequire(mod); + + mod.call = function(){ + if(cached) { + return mod.exports; + } + + cached = true; + + global.require = mod.require; + + mod.wrapper(mod, mod.exports, global, global.require); + return mod.exports; + }; + + if(parent.mainModuleId == mod.id){ + parent.index = mod; + parent.parents.length === 0 && ( main = mod.call ); + } + + parent.modules.push(mod); +} + +function pkg(/* [ parentId ...], wrapper */){ + var wrapper = arguments[ arguments.length - 1 ], + parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), + ctx = wrapper(parents); + + + pkgmap[ctx.name] = ctx; + + arguments.length == 1 && ( pkgmap.main = ctx ); + + return function(modules){ + var id; + for(id in modules){ + module(ctx, id, modules[id]); + } + }; +} + + +}(this)); + +bson.pkg(function(parents){ + + return { + 'name' : 'bson', + 'mainModuleId' : 'bson', + 'modules' : [], + 'parents' : parents + }; + +})({ 'binary': function(module, exports, global, require, undefined){ + /** + * 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; + + +}, + + + +'binary_parser': function(module, exports, global, require, undefined){ + /** + * 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; + +}, + + + +'bson': function(module, exports, global, require, undefined){ + var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class Represents the BSON Parser + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + var startIndex = index; + + switch(typeof value) { + case 'string': + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] || true; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00) { i++ } + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; + +}, + + + +'code': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'db_ref': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'double': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'float_parser': function(module, exports, global, require, undefined){ + // 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; +}, + + + +'index': function(module, exports, global, require, undefined){ + 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; +} + +}, + + + +'long': function(module, exports, global, require, undefined){ + // 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; +}, + + + +'max_key': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'min_key': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'objectid': function(module, exports, global, require, undefined){ + /** + * 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 { + 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 as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* 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 = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + 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 date (accurate up to the second) that this ID was generated. +* +* @return {Date} the generation date +* @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 = parseInt(Math.random() * 0xFFFFFF, 10); + +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; + +}, + + + +'symbol': function(module, exports, global, require, undefined){ + /** + * 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; +}, + + + +'timestamp': function(module, exports, global, require, undefined){ + // 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; +}, + + }); + + +if(typeof module != 'undefined' && module.exports ){ + module.exports = bson; + + if( !module.parent ){ + bson(); + } +} + +if(typeof window != 'undefined' && typeof require == 'undefined'){ + window.require = bson.require; +} diff --git a/node_modules/mongoose/node_modules/bson/browser_build/package.json b/node_modules/mongoose/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/browser_build/package.json @@ -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" } ] +} diff --git a/node_modules/bson/build_browser.js b/node_modules/mongoose/node_modules/bson/build_browser.js similarity index 100% rename from node_modules/bson/build_browser.js rename to node_modules/mongoose/node_modules/bson/build_browser.js diff --git a/node_modules/bson/builderror.log b/node_modules/mongoose/node_modules/bson/builderror.log similarity index 91% rename from node_modules/bson/builderror.log rename to node_modules/mongoose/node_modules/bson/builderror.log index 9b62dcf..86ccae4 100644 --- a/node_modules/bson/builderror.log +++ b/node_modules/mongoose/node_modules/bson/builderror.log @@ -6,7 +6,7 @@ gyp ERR! stack at C:\Program Files\nodejs\node_modules\npm\node_modules\grac gyp ERR! stack at FSReqWrap.oncomplete (fs.js:152:21) gyp ERR! System Windows_NT 10.0.16299 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" -gyp ERR! cwd E:\github\node-dc-mongo\node_modules\bson +gyp ERR! cwd E:\github\node-dc-mongo\node_modules\mongoose\node_modules\bson gyp ERR! node -v v8.12.0 gyp ERR! node-gyp -v v3.8.0 gyp ERR! not ok diff --git a/node_modules/bson/ext/Makefile b/node_modules/mongoose/node_modules/bson/ext/Makefile similarity index 100% rename from node_modules/bson/ext/Makefile rename to node_modules/mongoose/node_modules/bson/ext/Makefile diff --git a/node_modules/bson/ext/bson.cc b/node_modules/mongoose/node_modules/bson/ext/bson.cc similarity index 100% rename from node_modules/bson/ext/bson.cc rename to node_modules/mongoose/node_modules/bson/ext/bson.cc diff --git a/node_modules/bson/ext/bson.h b/node_modules/mongoose/node_modules/bson/ext/bson.h similarity index 100% rename from node_modules/bson/ext/bson.h rename to node_modules/mongoose/node_modules/bson/ext/bson.h diff --git a/node_modules/bson/ext/index.js b/node_modules/mongoose/node_modules/bson/ext/index.js similarity index 94% rename from node_modules/bson/ext/index.js rename to node_modules/mongoose/node_modules/bson/ext/index.js index 5550fcf..29232fd 100644 --- a/node_modules/bson/ext/index.js +++ b/node_modules/mongoose/node_modules/bson/ext/index.js @@ -7,12 +7,12 @@ try { } else if(process.platform == "win32" && process.arch == "ia32") { bson = require('./win32/ia32/bson'); } else { - bson = require('bson'); + bson = require('../browser_build/bson'); } } catch(err) { // Attempt to load the release bson version try { - bson = require('bson'); + bson = require('../browser_build/bson'); } catch (err) { console.dir(err) console.error("js-bson: Failed to load c++ bson extension, using pure JS version"); diff --git a/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/mongoose/node_modules/bson/ext/win32/ia32/bson.node similarity index 100% rename from node_modules/bson/ext/win32/ia32/bson.node rename to node_modules/mongoose/node_modules/bson/ext/win32/ia32/bson.node diff --git a/node_modules/bson/ext/win32/x64/bson.node b/node_modules/mongoose/node_modules/bson/ext/win32/x64/bson.node similarity index 100% rename from node_modules/bson/ext/win32/x64/bson.node rename to node_modules/mongoose/node_modules/bson/ext/win32/x64/bson.node diff --git a/node_modules/bson/ext/wscript b/node_modules/mongoose/node_modules/bson/ext/wscript similarity index 100% rename from node_modules/bson/ext/wscript rename to node_modules/mongoose/node_modules/bson/ext/wscript diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/binary.js b/node_modules/mongoose/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..5d0acfa --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * Module dependencies. + * @ignore + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * 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 + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +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. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +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. + * + * @method + * @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. + * @return {null} + */ +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**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +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. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // 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. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +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 + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +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. + */ +module.exports = Binary; +module.exports.Binary = Binary; \ No newline at end of file diff --git a/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js similarity index 100% rename from node_modules/bson/lib/bson/binary_parser.js rename to node_modules/mongoose/node_modules/bson/lib/bson/binary_parser.js diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/bson.js b/node_modules/mongoose/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..fc57600 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,1573 @@ +var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + var startIndex = index; + + switch(typeof value) { + case 'string': + // console.log("+++++++++++ index string:: " + index) + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // console.log("====== key :: " + name + " size ::" + size) + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // console.log("+++++++++++ index OBJECTID:: " + index) + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) + // console.log(buffer.toString('hex')) + // console.log(buffer.toString('ascii')) + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_UNDEFINED: + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; diff --git a/node_modules/bson/lib/bson/bson_new.js b/node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js similarity index 100% rename from node_modules/bson/lib/bson/bson_new.js rename to node_modules/mongoose/node_modules/bson/lib/bson/bson_new.js diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/code.js b/node_modules/mongoose/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var 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 + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @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 + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/double.js b/node_modules/mongoose/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @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. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/float_parser.js @@ -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; \ No newline at end of file diff --git a/node_modules/bson/lib/bson/index.js b/node_modules/mongoose/node_modules/bson/lib/bson/index.js similarity index 100% rename from node_modules/bson/lib/bson/index.js rename to node_modules/mongoose/node_modules/bson/lib/bson/index.js diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/long.js b/node_modules/mongoose/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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 + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +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. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +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. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +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. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @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. + */ +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. + * + * @method + * @return {Long} the negation of this value. + */ +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. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +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. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +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. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +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. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +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. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +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. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +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. + * + * @method + * @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. + */ +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. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +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. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +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. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @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. + */ +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} + * @ignore + */ +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} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +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} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js b/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js b/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js b/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..1d4894a --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,274 @@ +/** + * Module dependencies. + * @ignore + */ +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. + * @ignore + */ +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 +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + if(!(this instanceof ObjectID)) return new ObjectID(id); + if((id instanceof ObjectID)) return id; + + this._bsontype = 'ObjectID'; + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else 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; + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +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 +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {string} return the 12 byte id binary string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = parseInt(Date.now()/1000,10); + } + + 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 % 0xFFFF); + 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. +* @ignore +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherID) { + if(otherID == null) return false; + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +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 +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +/** +* @ignore +*/ +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. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +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. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +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); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) { + return false; + } else { + // Check specifically for hex correctness + if(typeof id == 'string' && id.length == 24) return checkForHexRegExp.test(id); + return true; + } +}; + +/** +* @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. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js b/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @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. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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 + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * 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 + * @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} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +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. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +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. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +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. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @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. + */ +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. + * + * @method + * @return {Timestamp} the negation of this value. + */ +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. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +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. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +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. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +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. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +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. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +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. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +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. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +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. + * + * @method + * @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. + */ +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. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +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. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +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. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @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. + */ +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} + * @ignore + */ +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} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +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} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/bson/package.json b/node_modules/mongoose/node_modules/bson/package.json new file mode 100644 index 0000000..961c17c --- /dev/null +++ b/node_modules/mongoose/node_modules/bson/package.json @@ -0,0 +1,77 @@ +{ + "_from": "bson@~0.2", + "_id": "bson@0.2.22", + "_inBundle": false, + "_integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", + "_location": "/mongoose/bson", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bson@~0.2", + "name": "bson", + "escapedName": "bson", + "rawSpec": "~0.2", + "saveSpec": null, + "fetchSpec": "~0.2" + }, + "_requiredBy": [ + "/mongoose/mongodb" + ], + "_resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", + "_shasum": "fcda103f26d0c074d5a52d50927db80fd02b4b39", + "_spec": "bson@~0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose\\node_modules\\mongodb", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "browser": "lib/bson/bson.js", + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "bundleDependencies": false, + "config": { + "native": false + }, + "contributors": [], + "dependencies": { + "nan": "~1.8" + }, + "deprecated": false, + "description": "A bson parser for node.js and the browser", + "devDependencies": { + "gleak": "0.2.3", + "nodeunit": "0.9.0", + "one": "2.X.X" + }, + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "homepage": "https://github.com/mongodb/js-bson#readme", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "licenses": [ + { + "type": "Apache License, Version 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0" + } + ], + "main": "./lib/bson/index", + "name": "bson", + "repository": { + "type": "git", + "url": "git://github.com/mongodb/js-bson.git" + }, + "scripts": { + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" + }, + "version": "0.2.22" +} diff --git a/node_modules/bson/tools/gleak.js b/node_modules/mongoose/node_modules/bson/tools/gleak.js similarity index 100% rename from node_modules/bson/tools/gleak.js rename to node_modules/mongoose/node_modules/bson/tools/gleak.js diff --git a/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE similarity index 100% rename from node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE rename to node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE diff --git a/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js similarity index 100% rename from node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js rename to node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js diff --git a/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine.css similarity index 100% rename from node_modules/bson/tools/jasmine-1.1.0/jasmine.css rename to node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine.css diff --git a/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine.js similarity index 100% rename from node_modules/bson/tools/jasmine-1.1.0/jasmine.js rename to node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine.js diff --git a/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png similarity index 100% rename from node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png rename to node_modules/mongoose/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png diff --git a/node_modules/mongodb/.gitmodules b/node_modules/mongoose/node_modules/mongodb/.gitmodules similarity index 100% rename from node_modules/mongodb/.gitmodules rename to node_modules/mongoose/node_modules/mongodb/.gitmodules diff --git a/node_modules/mongodb/.travis.yml b/node_modules/mongoose/node_modules/mongodb/.travis.yml similarity index 100% rename from node_modules/mongodb/.travis.yml rename to node_modules/mongoose/node_modules/mongodb/.travis.yml diff --git a/node_modules/mongodb/CONTRIBUTING.md b/node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md similarity index 100% rename from node_modules/mongodb/CONTRIBUTING.md rename to node_modules/mongoose/node_modules/mongodb/CONTRIBUTING.md diff --git a/node_modules/mongodb/HISTORY b/node_modules/mongoose/node_modules/mongodb/HISTORY similarity index 100% rename from node_modules/mongodb/HISTORY rename to node_modules/mongoose/node_modules/mongodb/HISTORY diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE b/node_modules/mongoose/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/node_modules/mongodb/Makefile b/node_modules/mongoose/node_modules/mongodb/Makefile similarity index 100% rename from node_modules/mongodb/Makefile rename to node_modules/mongoose/node_modules/mongodb/Makefile diff --git a/node_modules/mongoose/node_modules/mongodb/Readme.md b/node_modules/mongoose/node_modules/mongodb/Readme.md new file mode 100644 index 0000000..5e4877d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/Readme.md @@ -0,0 +1,418 @@ +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) +- Valeri Karpov [@code_barbarian](https://twitter.com/code_barbarian) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +## 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 + +## Live Examples + + +## 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 MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { + if(err) throw err; + + var collection = db.collection('test_insert'); + collection.insert({a:2}, function(err, docs) { + + collection.count(function(err, count) { + console.log(format("count = %s", count)); + }); + + // Locate all the entries using find + collection.find().toArray(function(err, results) { + console.dir(results); + // Let's close the db + db.close(); + }); + }); + }) +``` + +## 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: + MongoClient.connect('mongodb://127.0.0.1:27017/test' + , {db: {native_parser: true}}, function(err, db) {}) +``` + +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 + + $ node test/runner.js -t functional + +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 the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) + +### 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 + var MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + // Custom factory (need to provide a 12 byte array); + CustomPKFactory = function() {} + CustomPKFactory.prototype = new Object(); + CustomPKFactory.createPk = function() { + return new ObjectID("aaaaaaaaaaaa"); + } + + MongoClient.connect('mongodb://127.0.0.1:27017/test', {'pkFactory':CustomPKFactory}, function(err, db) { + if(err) throw err; + + db.dropDatabase(function(err, done) { + + db.createCollection('test_custom_key', function(err, collection) { + + collection.insert({'a':1}, function(err, docs) { + + collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { + console.dir(items); + // Let's close the db + db.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 MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { + if(err) throw err; + + var collection = db + .collection('test') + .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: + +* `w:1` Should always set if you have a callback. + +See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). + +```javascript + var MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { + if(err) throw err; + + db.collection('test').insert({hello: 'world'}, {w:1}, 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 `w:1` option. If you don't specify `w:1`, 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 `w:1`, `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: + +* `w:1` 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 MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { + if(err) throw err; + + db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, 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 MongoClient = require('mongodb').MongoClient + , format = require('util').format; + + MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { + if(err) throw err; + db.collection('test').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`. + +## 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 - 2013 MongoDb Inc. + + 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. + diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/index.js new file mode 100644 index 0000000..4f59e9d --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/mongodb'); diff --git a/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/admin.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/admin.js diff --git a/node_modules/mongodb/lib/mongodb/aggregation_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/aggregation_cursor.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/aggregation_cursor.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/aggregation_cursor.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_scram.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js diff --git a/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection.js diff --git a/node_modules/mongodb/lib/mongodb/collection/aggregation.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/aggregation.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/aggregation.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/aggregation.js diff --git a/node_modules/mongodb/lib/mongodb/collection/batch/common.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/common.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/batch/common.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/common.js diff --git a/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/batch/ordered.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js diff --git a/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/batch/unordered.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/batch/unordered.js diff --git a/node_modules/mongodb/lib/mongodb/collection/commands.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/commands.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/commands.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/commands.js diff --git a/node_modules/mongodb/lib/mongodb/collection/core.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/core.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/core.js diff --git a/node_modules/mongodb/lib/mongodb/collection/geo.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/geo.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/geo.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/geo.js diff --git a/node_modules/mongodb/lib/mongodb/collection/index.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/index.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/index.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/index.js diff --git a/node_modules/mongodb/lib/mongodb/collection/query.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/query.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/query.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/query.js diff --git a/node_modules/mongodb/lib/mongodb/collection/shared.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/shared.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/collection/shared.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/collection/shared.js diff --git a/node_modules/mongodb/lib/mongodb/command_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/command_cursor.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/command_cursor.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/command_cursor.js diff --git a/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/base_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/base_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/db_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/db_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/delete_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/delete_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/get_more_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/get_more_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/insert_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/insert_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/query_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/query_command.js diff --git a/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/commands/update_command.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/commands/update_command.js diff --git a/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/base.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js diff --git a/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/connection.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js diff --git a/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/connection_pool.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js diff --git a/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/connection_utils.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_utils.js diff --git a/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/mongos.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js diff --git a/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/read_preference.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/read_preference.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/options.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js diff --git a/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/server.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js diff --git a/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/server_capabilities.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js diff --git a/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/connection/url_parser.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js diff --git a/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/cursor.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursor.js diff --git a/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/cursorstream.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/cursorstream.js diff --git a/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/db.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js diff --git a/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/gridfs/chunk.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js diff --git a/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/gridfs/grid.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js diff --git a/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/gridfs/gridstore.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js diff --git a/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/gridfs/readstream.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js diff --git a/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/index.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/index.js diff --git a/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/mongo_client.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js diff --git a/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/responses/mongo_reply.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js diff --git a/node_modules/mongodb/lib/mongodb/scope.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/scope.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/scope.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/scope.js diff --git a/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js similarity index 100% rename from node_modules/mongodb/lib/mongodb/utils.js rename to node_modules/mongoose/node_modules/mongodb/lib/mongodb/utils.js diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mongodb/package.json new file mode 100644 index 0000000..b3e5c61 --- /dev/null +++ b/node_modules/mongoose/node_modules/mongodb/package.json @@ -0,0 +1,255 @@ +{ + "_from": "mongodb@1.4.38", + "_id": "mongodb@1.4.38", + "_inBundle": false, + "_integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "_location": "/mongoose/mongodb", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mongodb@1.4.38", + "name": "mongodb", + "escapedName": "mongodb", + "rawSpec": "1.4.38", + "saveSpec": null, + "fetchSpec": "1.4.38" + }, + "_requiredBy": [ + "/mongoose" + ], + "_resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", + "_shasum": "8cffd618100af3a4648a995498bfcfcb4ed8abd2", + "_spec": "mongodb@1.4.38", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongoose", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "bugs": { + "url": "http://github.com/mongodb/node-mongodb-native/issues" + }, + "bundleDependencies": false, + "config": { + "native": false + }, + "contributors": [ + { + "name": "Aaron Heckmann" + }, + { + "name": "Christoph Pojer" + }, + { + "name": "Pau Ramon Revilla" + }, + { + "name": "Nathan White" + }, + { + "name": "Emmerman" + }, + { + "name": "Seth LaForge" + }, + { + "name": "Boris Filipov" + }, + { + "name": "Stefan Schärmeli" + }, + { + "name": "Tedde Lundgren" + }, + { + "name": "renctan" + }, + { + "name": "Sergey Ukustov" + }, + { + "name": "Ciaran Jessup" + }, + { + "name": "kuno" + }, + { + "name": "srimonti" + }, + { + "name": "Erik Abele" + }, + { + "name": "Pratik Daga" + }, + { + "name": "Slobodan Utvic" + }, + { + "name": "Kristina Chodorow" + }, + { + "name": "Yonathan Randolph" + }, + { + "name": "Brian Noguchi" + }, + { + "name": "Sam Epstein" + }, + { + "name": "James Harrison Fisher" + }, + { + "name": "Vladimir Dronnikov" + }, + { + "name": "Ben Hockey" + }, + { + "name": "Henrik Johansson" + }, + { + "name": "Simon Weare" + }, + { + "name": "Alex Gorbatchev" + }, + { + "name": "Shimon Doodkin" + }, + { + "name": "Kyle Mueller" + }, + { + "name": "Eran Hammer-Lahav" + }, + { + "name": "Marcin Ciszak" + }, + { + "name": "François de Metz" + }, + { + "name": "Vinay Pulim" + }, + { + "name": "nstielau" + }, + { + "name": "Adam Wiggins" + }, + { + "name": "entrinzikyl" + }, + { + "name": "Jeremy Selier" + }, + { + "name": "Ian Millington" + }, + { + "name": "Public Keating" + }, + { + "name": "andrewjstone" + }, + { + "name": "Christopher Stott" + }, + { + "name": "Corey Jewett" + }, + { + "name": "brettkiefer" + }, + { + "name": "Rob Holland" + }, + { + "name": "Senmiao Liu" + }, + { + "name": "heroic" + }, + { + "name": "gitfy" + }, + { + "name": "Andrew Stone" + }, + { + "name": "John Le Drew" + }, + { + "name": "Lucasfilm Singapore" + }, + { + "name": "Roman Shtylman" + }, + { + "name": "Matt Self" + }, + { + "name": "Gregory Langlais" + }, + { + "name": "Samantha Ritter" + } + ], + "dependencies": { + "bson": "~0.2", + "kerberos": "0.0.11", + "readable-stream": "latest" + }, + "deprecated": "Please upgrade to 2.2.19 or higher", + "description": "A node.js driver for MongoDB", + "devDependencies": { + "dox": "0.4.4", + "ejs": "0.6.1", + "gleak": "0.5.0", + "integra": "0.1.8", + "markdown": "0.3.1", + "mongodb-tools": "~1.0", + "mongodb-version-manager": "0.7.0", + "nodeunit": "0.7.3", + "optimist": "latest", + "request": "2.12.0", + "rimraf": "2.2.6", + "semver": "4.1.0", + "uglify-js": "1.2.5" + }, + "directories": { + "lib": "./lib/mongodb" + }, + "engines": { + "node": ">=0.6.19" + }, + "homepage": "http://mongodb.github.com/node-mongodb-native/", + "keywords": [ + "mongodb", + "mongo", + "driver", + "db" + ], + "licenses": [ + { + "type": "Apache License, Version 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0" + } + ], + "main": "./lib/mongodb/index", + "name": "mongodb", + "optionalDependencies": { + "kerberos": "0.0.11", + "readable-stream": "latest" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "scripts": { + "test": "node test/runner.js -t functional" + }, + "version": "1.4.38" +} diff --git a/node_modules/mongodb/repo_node_418.js b/node_modules/mongoose/node_modules/mongodb/repo_node_418.js similarity index 100% rename from node_modules/mongodb/repo_node_418.js rename to node_modules/mongoose/node_modules/mongodb/repo_node_418.js diff --git a/node_modules/mongodb/wercker.yml b/node_modules/mongoose/node_modules/mongodb/wercker.yml similarity index 100% rename from node_modules/mongodb/wercker.yml rename to node_modules/mongoose/node_modules/mongodb/wercker.yml diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/.npmignore b/node_modules/negotiator/.npmignore similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/.npmignore rename to node_modules/negotiator/.npmignore diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/LICENSE rename to node_modules/negotiator/LICENSE diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/lib/charset.js rename to node_modules/negotiator/lib/charset.js diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/lib/encoding.js rename to node_modules/negotiator/lib/encoding.js diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/lib/language.js rename to node_modules/negotiator/lib/language.js diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/lib/mediaType.js rename to node_modules/negotiator/lib/mediaType.js diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js b/node_modules/negotiator/lib/negotiator.js similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/lib/negotiator.js rename to node_modules/negotiator/lib/negotiator.js diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json b/node_modules/negotiator/package.json similarity index 72% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/package.json rename to node_modules/negotiator/package.json index 73193ba..fda150a 100644 --- a/node_modules/express/node_modules/accepts/node_modules/negotiator/package.json +++ b/node_modules/negotiator/package.json @@ -1,11 +1,40 @@ { - "name": "negotiator", - "description": "HTTP content negotiation", - "version": "0.4.7", + "_from": "negotiator@0.4.7", + "_id": "negotiator@0.4.7", + "_inBundle": false, + "_integrity": "sha1-pBYPcXfsgGc4Yx0NMFIyXaQqvcg=", + "_location": "/negotiator", + "_npmUser": { + "name": "federomero", + "email": "federomero@gmail.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "negotiator@0.4.7", + "name": "negotiator", + "escapedName": "negotiator", + "rawSpec": "0.4.7", + "saveSpec": null, + "fetchSpec": "0.4.7" + }, + "_requiredBy": [ + "/accepts" + ], + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz", + "_shasum": "a4160f7177ec806738631d0d3052325da42abdc8", + "_spec": "negotiator@0.4.7", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\accepts", "author": { "name": "Federico Romero", "email": "federico.romero@outboxlabs.com" }, + "bugs": { + "url": "https://github.com/federomero/negotiator/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Isaac Z. Schlueter", @@ -13,10 +42,22 @@ "url": "http://blog.izs.me/" } ], - "repository": { - "type": "git", - "url": "git://github.com/federomero/negotiator.git" + "dependencies": {}, + "deprecated": false, + "description": "HTTP content negotiation", + "devDependencies": { + "nodeunit": "0.8.x" + }, + "directories": {}, + "dist": { + "shasum": "a4160f7177ec806738631d0d3052325da42abdc8", + "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz" }, + "engine": "node >= 0.6", + "engines": { + "node": "*" + }, + "homepage": "https://github.com/federomero/negotiator", "keywords": [ "http", "content negotiation", @@ -25,42 +66,22 @@ "accept-encoding", "accept-charset" ], - "engine": "node >= 0.6", "license": "MIT", - "devDependencies": { - "nodeunit": "0.8.x" - }, - "scripts": { - "test": "nodeunit test" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, "main": "lib/negotiator.js", - "bugs": { - "url": "https://github.com/federomero/negotiator/issues" - }, - "homepage": "https://github.com/federomero/negotiator", - "dependencies": {}, - "_id": "negotiator@0.4.7", - "dist": { - "shasum": "a4160f7177ec806738631d0d3052325da42abdc8", - "tarball": "http://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz" - }, - "_from": "negotiator@0.4.7", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "federomero", - "email": "federomero@gmail.com" - }, "maintainers": [ { "name": "federomero", "email": "federomero@gmail.com" } ], - "directories": {}, - "_shasum": "a4160f7177ec806738631d0d3052325da42abdc8", - "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz" + "name": "negotiator", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/federomero/negotiator.git" + }, + "scripts": { + "test": "nodeunit test" + }, + "version": "0.4.7" } diff --git a/node_modules/express/node_modules/accepts/node_modules/negotiator/readme.md b/node_modules/negotiator/readme.md similarity index 100% rename from node_modules/express/node_modules/accepts/node_modules/negotiator/readme.md rename to node_modules/negotiator/readme.md diff --git a/node_modules/express/node_modules/parseurl/.npmignore b/node_modules/parseurl/.npmignore similarity index 100% rename from node_modules/express/node_modules/parseurl/.npmignore rename to node_modules/parseurl/.npmignore diff --git a/node_modules/express/node_modules/parseurl/README.md b/node_modules/parseurl/README.md similarity index 100% rename from node_modules/express/node_modules/parseurl/README.md rename to node_modules/parseurl/README.md diff --git a/node_modules/express/node_modules/parseurl/index.js b/node_modules/parseurl/index.js similarity index 100% rename from node_modules/express/node_modules/parseurl/index.js rename to node_modules/parseurl/index.js diff --git a/node_modules/express/node_modules/parseurl/package.json b/node_modules/parseurl/package.json similarity index 61% rename from node_modules/express/node_modules/parseurl/package.json rename to node_modules/parseurl/package.json index 658ee6d..5f2a576 100644 --- a/node_modules/express/node_modules/parseurl/package.json +++ b/node_modules/parseurl/package.json @@ -1,41 +1,62 @@ { - "name": "parseurl", - "description": "parse a url with memoization", - "version": "1.0.1", + "_from": "parseurl@1.0.1", + "_id": "parseurl@1.0.1", + "_inBundle": false, + "_integrity": "sha1-Llfc5u/dN8NRhwEDCUTCK/OIt7Q=", + "_location": "/parseurl", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "_npmVersion": "1.4.4", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "parseurl@1.0.1", + "name": "parseurl", + "escapedName": "parseurl", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", + "_shasum": "2e57dce6efdd37c3518701030944c22bf388b7b4", + "_spec": "parseurl@1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "repository": { - "type": "git", - "url": "https://github.com/expressjs/parseurl.git" - }, "bugs": { "url": "https://github.com/expressjs/parseurl/issues", "email": "me@jongleberry.com" }, - "license": "MIT", - "homepage": "https://github.com/expressjs/parseurl", - "_id": "parseurl@1.0.1", + "bundleDependencies": false, + "deprecated": false, + "description": "parse a url with memoization", + "directories": {}, "dist": { "shasum": "2e57dce6efdd37c3518701030944c22bf388b7b4", "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz" }, - "_from": "parseurl@1.0.1", - "_npmVersion": "1.4.4", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, + "homepage": "https://github.com/expressjs/parseurl", + "license": "MIT", "maintainers": [ { "name": "jongleberry", "email": "jonathanrichardong@gmail.com" } ], - "directories": {}, - "_shasum": "2e57dce6efdd37c3518701030944c22bf388b7b4", - "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", - "scripts": {} + "name": "parseurl", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/parseurl.git" + }, + "scripts": {}, + "version": "1.0.1" } diff --git a/node_modules/express/node_modules/path-to-regexp/.npmignore b/node_modules/path-to-regexp/.npmignore similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/.npmignore rename to node_modules/path-to-regexp/.npmignore diff --git a/node_modules/express/node_modules/path-to-regexp/History.md b/node_modules/path-to-regexp/History.md similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/History.md rename to node_modules/path-to-regexp/History.md diff --git a/node_modules/express/node_modules/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/Readme.md rename to node_modules/path-to-regexp/Readme.md diff --git a/node_modules/express/node_modules/path-to-regexp/component.json b/node_modules/path-to-regexp/component.json similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/component.json rename to node_modules/path-to-regexp/component.json diff --git a/node_modules/express/node_modules/path-to-regexp/index.js b/node_modules/path-to-regexp/index.js similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/index.js rename to node_modules/path-to-regexp/index.js diff --git a/node_modules/express/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json similarity index 78% rename from node_modules/express/node_modules/path-to-regexp/package.json rename to node_modules/path-to-regexp/package.json index 0a536e1..0a8393c 100644 --- a/node_modules/express/node_modules/path-to-regexp/package.json +++ b/node_modules/path-to-regexp/package.json @@ -1,42 +1,57 @@ { - "name": "path-to-regexp", - "description": "Express style path to RegExp utility", - "version": "0.1.2", - "scripts": { - "test": "istanbul cover _mocha -- -R spec" + "_from": "path-to-regexp@0.1.2", + "_id": "path-to-regexp@0.1.2", + "_inBundle": false, + "_integrity": "sha1-mysVH5zDAYye6lDKlXKeBXgXErQ=", + "_location": "/path-to-regexp", + "_npmUser": { + "name": "blakeembrey", + "email": "hello@blakeembrey.com" }, - "keywords": [ - "express", - "regexp" + "_npmVersion": "1.4.4", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "path-to-regexp@0.1.2", + "name": "path-to-regexp", + "escapedName": "path-to-regexp", + "rawSpec": "0.1.2", + "saveSpec": null, + "fetchSpec": "0.1.2" + }, + "_requiredBy": [ + "/express" ], + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz", + "_shasum": "9b2b151f9cc3018c9eea50ca95729e05781712b4", + "_spec": "path-to-regexp@0.1.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "path-to-regexp": "index.js" } }, - "repository": { - "type": "git", - "url": "https://github.com/component/path-to-regexp.git" - }, + "deprecated": false, + "description": "Express style path to RegExp utility", "devDependencies": { - "mocha": "^1.17.1", - "istanbul": "^0.2.6" - }, - "bugs": { - "url": "https://github.com/component/path-to-regexp/issues" + "istanbul": "^0.2.6", + "mocha": "^1.17.1" }, - "homepage": "https://github.com/component/path-to-regexp", - "_id": "path-to-regexp@0.1.2", + "directories": {}, "dist": { "shasum": "9b2b151f9cc3018c9eea50ca95729e05781712b4", "tarball": "http://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz" }, - "_from": "path-to-regexp@0.1.2", - "_npmVersion": "1.4.4", - "_npmUser": { - "name": "blakeembrey", - "email": "hello@blakeembrey.com" - }, + "homepage": "https://github.com/component/path-to-regexp", + "keywords": [ + "express", + "regexp" + ], "maintainers": [ { "name": "tjholowaychuk", @@ -123,7 +138,13 @@ "email": "hello@blakeembrey.com" } ], - "directories": {}, - "_shasum": "9b2b151f9cc3018c9eea50ca95729e05781712b4", - "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz" + "name": "path-to-regexp", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "version": "0.1.2" } diff --git a/node_modules/express/node_modules/path-to-regexp/test.js b/node_modules/path-to-regexp/test.js similarity index 100% rename from node_modules/express/node_modules/path-to-regexp/test.js rename to node_modules/path-to-regexp/test.js diff --git a/node_modules/express/node_modules/proxy-addr/.npmignore b/node_modules/proxy-addr/.npmignore similarity index 100% rename from node_modules/express/node_modules/proxy-addr/.npmignore rename to node_modules/proxy-addr/.npmignore diff --git a/node_modules/express/node_modules/proxy-addr/History.md b/node_modules/proxy-addr/History.md similarity index 100% rename from node_modules/express/node_modules/proxy-addr/History.md rename to node_modules/proxy-addr/History.md diff --git a/node_modules/express/node_modules/proxy-addr/LICENSE b/node_modules/proxy-addr/LICENSE similarity index 100% rename from node_modules/express/node_modules/proxy-addr/LICENSE rename to node_modules/proxy-addr/LICENSE diff --git a/node_modules/express/node_modules/proxy-addr/README.md b/node_modules/proxy-addr/README.md similarity index 100% rename from node_modules/express/node_modules/proxy-addr/README.md rename to node_modules/proxy-addr/README.md diff --git a/node_modules/express/node_modules/proxy-addr/index.js b/node_modules/proxy-addr/index.js similarity index 100% rename from node_modules/express/node_modules/proxy-addr/index.js rename to node_modules/proxy-addr/index.js diff --git a/node_modules/express/node_modules/proxy-addr/package.json b/node_modules/proxy-addr/package.json similarity index 75% rename from node_modules/express/node_modules/proxy-addr/package.json rename to node_modules/proxy-addr/package.json index 532d3cf..3859c6b 100644 --- a/node_modules/express/node_modules/proxy-addr/package.json +++ b/node_modules/proxy-addr/package.json @@ -1,55 +1,67 @@ { - "name": "proxy-addr", - "description": "Determine address of proxied request", - "version": "1.0.1", - "author": { - "name": "Douglas Christopher Wilson", + "_from": "proxy-addr@1.0.1", + "_id": "proxy-addr@1.0.1", + "_inBundle": false, + "_integrity": "sha1-x8Vm1etOP61n7rnHfFVYzMObiKg=", + "_location": "/proxy-addr", + "_npmUser": { + "name": "dougwilson", "email": "doug@somethingdoug.com" }, - "license": "MIT", - "keywords": [ - "ip", - "proxy", - "x-forwarded-for" + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "proxy-addr@1.0.1", + "name": "proxy-addr", + "escapedName": "proxy-addr", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express" ], - "repository": { - "type": "git", - "url": "https://github.com/expressjs/proxy-addr.git" + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz", + "_shasum": "c7c566d5eb4e3fad67eeb9c77c5558ccc39b88a8", + "_spec": "proxy-addr@1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" }, "bugs": { "url": "https://github.com/expressjs/proxy-addr/issues" }, + "bundleDependencies": false, "dependencies": { "ipaddr.js": "0.1.2" }, + "deprecated": false, + "description": "Determine address of proxied request", "devDependencies": { - "benchmark": "1.0.0", "beautify-benchmark": "0.2.4", + "benchmark": "1.0.0", "istanbul": "0.2.10", "mocha": "~1.20.0", "should": "~4.0.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "bench": "node benchmark/index.js", - "test": "mocha --reporter dot test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "homepage": "https://github.com/expressjs/proxy-addr", - "_id": "proxy-addr@1.0.1", + "directories": {}, "dist": { "shasum": "c7c566d5eb4e3fad67eeb9c77c5558ccc39b88a8", "tarball": "http://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz" }, - "_from": "proxy-addr@1.0.1", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/proxy-addr", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "license": "MIT", "maintainers": [ { "name": "dougwilson", @@ -76,7 +88,16 @@ "email": "fishrock123@rocketmail.com" } ], - "directories": {}, - "_shasum": "c7c566d5eb4e3fad67eeb9c77c5558ccc39b88a8", - "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz" + "name": "proxy-addr", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/proxy-addr.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "version": "1.0.1" } diff --git a/node_modules/express/node_modules/qs/.gitmodules b/node_modules/qs/.gitmodules similarity index 100% rename from node_modules/express/node_modules/qs/.gitmodules rename to node_modules/qs/.gitmodules diff --git a/node_modules/express/node_modules/qs/.npmignore b/node_modules/qs/.npmignore similarity index 100% rename from node_modules/express/node_modules/qs/.npmignore rename to node_modules/qs/.npmignore diff --git a/node_modules/express/node_modules/qs/Readme.md b/node_modules/qs/Readme.md similarity index 100% rename from node_modules/express/node_modules/qs/Readme.md rename to node_modules/qs/Readme.md diff --git a/node_modules/express/node_modules/qs/index.js b/node_modules/qs/index.js similarity index 100% rename from node_modules/express/node_modules/qs/index.js rename to node_modules/qs/index.js diff --git a/node_modules/express/node_modules/qs/package.json b/node_modules/qs/package.json similarity index 59% rename from node_modules/express/node_modules/qs/package.json rename to node_modules/qs/package.json index 6e5849f..d77b4bb 100644 --- a/node_modules/express/node_modules/qs/package.json +++ b/node_modules/qs/package.json @@ -1,53 +1,75 @@ { - "name": "qs", - "description": "querystring parser", - "version": "0.6.6", - "keywords": [ - "query string", - "parser", - "component" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*", - "expect.js": "*" + "_from": "qs@0.6.6", + "_id": "qs@0.6.6", + "_inBundle": false, + "_integrity": "sha1-bgFQmP9RlouKPIGQAdXyyJvEsQc=", + "_location": "/qs", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" }, - "scripts": { - "test": "make test" + "_npmVersion": "1.2.30", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "qs@0.6.6", + "name": "qs", + "escapedName": "qs", + "rawSpec": "0.6.6", + "saveSpec": null, + "fetchSpec": "0.6.6" }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz", + "_shasum": "6e015098ff51968b8a3c819001d5f2c89bc4b107", + "_spec": "qs@0.6.6", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca", "url": "http://tjholowaychuk.com" }, - "main": "index", - "engines": { - "node": "*" - }, "bugs": { "url": "https://github.com/visionmedia/node-querystring/issues" }, - "_id": "qs@0.6.6", + "bundleDependencies": false, + "deprecated": false, + "description": "querystring parser", + "devDependencies": { + "expect.js": "*", + "mocha": "*" + }, + "directories": {}, "dist": { "shasum": "6e015098ff51968b8a3c819001d5f2c89bc4b107", "tarball": "http://registry.npmjs.org/qs/-/qs-0.6.6.tgz" }, - "_from": "qs@0.6.6", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" + "engines": { + "node": "*" }, + "homepage": "https://github.com/visionmedia/node-querystring#readme", + "keywords": [ + "query string", + "parser", + "component" + ], + "main": "index", "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "6e015098ff51968b8a3c819001d5f2c89bc4b107", - "_resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz" + "name": "qs", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/node-querystring.git" + }, + "scripts": { + "test": "make test" + }, + "version": "0.6.6" } diff --git a/node_modules/express/node_modules/range-parser/.npmignore b/node_modules/range-parser/.npmignore similarity index 100% rename from node_modules/express/node_modules/range-parser/.npmignore rename to node_modules/range-parser/.npmignore diff --git a/node_modules/express/node_modules/range-parser/History.md b/node_modules/range-parser/History.md similarity index 100% rename from node_modules/express/node_modules/range-parser/History.md rename to node_modules/range-parser/History.md diff --git a/node_modules/express/node_modules/range-parser/Makefile b/node_modules/range-parser/Makefile similarity index 100% rename from node_modules/express/node_modules/range-parser/Makefile rename to node_modules/range-parser/Makefile diff --git a/node_modules/express/node_modules/range-parser/Readme.md b/node_modules/range-parser/Readme.md similarity index 100% rename from node_modules/express/node_modules/range-parser/Readme.md rename to node_modules/range-parser/Readme.md diff --git a/node_modules/express/node_modules/range-parser/index.js b/node_modules/range-parser/index.js similarity index 100% rename from node_modules/express/node_modules/range-parser/index.js rename to node_modules/range-parser/index.js diff --git a/node_modules/express/node_modules/range-parser/package.json b/node_modules/range-parser/package.json similarity index 59% rename from node_modules/express/node_modules/range-parser/package.json rename to node_modules/range-parser/package.json index 0bd4072..16c7009 100644 --- a/node_modules/express/node_modules/range-parser/package.json +++ b/node_modules/range-parser/package.json @@ -1,49 +1,73 @@ { - "name": "range-parser", + "_from": "range-parser@1.0.0", + "_id": "range-parser@1.0.0", + "_inBundle": false, + "_integrity": "sha1-pLJkz+C+XONqvjdlrJwqJIdG28A=", + "_location": "/range-parser", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "_npmVersion": "1.2.30", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "range-parser@1.0.0", + "name": "range-parser", + "escapedName": "range-parser", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/express", + "/send", + "/serve-static/send" + ], + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz", + "_shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", + "_spec": "range-parser@1.0.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca", "url": "http://tjholowaychuk.com" }, - "description": "Range header field string parser", - "version": "1.0.0", - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/node-range-parser.git" + "bugs": { + "url": "https://github.com/visionmedia/node-range-parser/issues" }, - "main": "index.js", + "bundleDependencies": false, "dependencies": {}, + "deprecated": false, + "description": "Range header field string parser", "devDependencies": { "mocha": "*", "should": "*" }, + "directories": {}, + "dist": { + "shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", + "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz" + }, + "homepage": "https://github.com/visionmedia/node-range-parser#readme", "licenses": [ { "type": "MIT", "url": "https://github.com/visionmedia/node-range-parser#license" } ], - "bugs": { - "url": "https://github.com/visionmedia/node-range-parser/issues" - }, - "_id": "range-parser@1.0.0", - "dist": { - "shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", - "tarball": "http://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz" - }, - "_from": "range-parser@1.0.0", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, + "main": "index.js", "maintainers": [ { "name": "tjholowaychuk", "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "a4b264cfe0be5ce36abe3765ac9c2a248746dbc0", - "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz" + "name": "range-parser", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-range-parser.git" + }, + "version": "1.0.0" } diff --git a/node_modules/require_optional/.npmignore b/node_modules/require_optional/.npmignore new file mode 100644 index 0000000..e920c16 --- /dev/null +++ b/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/node_modules/require_optional/.travis.yml b/node_modules/require_optional/.travis.yml new file mode 100644 index 0000000..72903c3 --- /dev/null +++ b/node_modules/require_optional/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "6" + - "7" + - "8" +sudo: false diff --git a/node_modules/require_optional/HISTORY.md b/node_modules/require_optional/HISTORY.md new file mode 100644 index 0000000..7bee02f --- /dev/null +++ b/node_modules/require_optional/HISTORY.md @@ -0,0 +1,7 @@ +1.0.1 03-02-2016 +================ +* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. + +1.0.0 03-02-2016 +================ +* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/node_modules/require_optional/LICENSE b/node_modules/require_optional/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/node_modules/require_optional/README.md b/node_modules/require_optional/README.md new file mode 100644 index 0000000..c0323f0 --- /dev/null +++ b/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/node_modules/require_optional/index.js b/node_modules/require_optional/index.js new file mode 100644 index 0000000..3710319 --- /dev/null +++ b/node_modules/require_optional/index.js @@ -0,0 +1,128 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +// Find the location of a package.json file near or above the given location +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies +var find_package_json_with_name = function(name) { + // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies + var currentModule = module; + var found = false; + while (currentModule) { + // Check currentModule has a package.json + location = currentModule.filename; + var location = find_package_json(location) + if (!location) { + currentModule = currentModule.parent; + continue; + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for + if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { + currentModule = currentModule.parent; + continue; + } + found = true; + break; + } + + // Check whether name has been found in currentModule's peerOptionalDependencies + if (!found) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); + } + + return { + object: object, + parts: parts + } +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + var res = find_package_json_with_name(name) + var object = res.object; + var parts = res.parts; + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/node_modules/require_optional/package.json b/node_modules/require_optional/package.json new file mode 100644 index 0000000..b3d6c43 --- /dev/null +++ b/node_modules/require_optional/package.json @@ -0,0 +1,67 @@ +{ + "_from": "require_optional@^1.0.1", + "_id": "require_optional@1.0.1", + "_inBundle": false, + "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "_location": "/require_optional", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "require_optional@^1.0.1", + "name": "require_optional", + "escapedName": "require_optional", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/mongodb-core" + ], + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", + "_spec": "require_optional@^1.0.1", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb-core", + "author": { + "name": "Christian Kvalheim Amor" + }, + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "bundleDependencies": false, + "dependencies": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + }, + "deprecated": false, + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "homepage": "https://github.com/christkv/require_optional", + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "require_optional", + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/require_optional.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "1.0.1" +} diff --git a/node_modules/require_optional/test/nestedTest/index.js b/node_modules/require_optional/test/nestedTest/index.js new file mode 100644 index 0000000..76de2ab --- /dev/null +++ b/node_modules/require_optional/test/nestedTest/index.js @@ -0,0 +1,8 @@ +var require_optional = require('../../') + +function findPackage(packageName) { + var pkg = require_optional(packageName); + return pkg; +} + +module.exports.findPackage = findPackage diff --git a/node_modules/require_optional/test/nestedTest/package.json b/node_modules/require_optional/test/nestedTest/package.json new file mode 100644 index 0000000..4c456a6 --- /dev/null +++ b/node_modules/require_optional/test/nestedTest/package.json @@ -0,0 +1,11 @@ +{ + "name": "nestedtest", + "version": "1.0.0", + "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Sebastian Hallum Clarke", + "license": "ISC" +} diff --git a/node_modules/require_optional/test/require_optional_tests.js b/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 0000000..c9cc2a3 --- /dev/null +++ b/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,59 @@ +var assert = require('assert'), + require_optional = require('../'), + nestedTest = require('./nestedTest'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); + + describe('require_optional inside dependencies', function() { + it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { + assert.ok(nestedTest.findPackage('bson')) + }); + it('should return null when a package is defined in top-level package.json but not installed', function() { + assert.equal(null, nestedTest.findPackage('es6-promise2')) + }); + it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { + try { + nestedTest.findPackage('bison') + } catch (err) { + assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') + } + }) + }); +}); diff --git a/node_modules/resolve-from/index.js b/node_modules/resolve-from/index.js new file mode 100644 index 0000000..434159f --- /dev/null +++ b/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/node_modules/resolve-from/license b/node_modules/resolve-from/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/resolve-from/package.json b/node_modules/resolve-from/package.json new file mode 100644 index 0000000..dab0ab0 --- /dev/null +++ b/node_modules/resolve-from/package.json @@ -0,0 +1,66 @@ +{ + "_from": "resolve-from@^2.0.0", + "_id": "resolve-from@2.0.0", + "_inBundle": false, + "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", + "_location": "/resolve-from", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "resolve-from@^2.0.0", + "name": "resolve-from", + "escapedName": "resolve-from", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_spec": "resolve-from@^2.0.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\require_optional", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Resolve the path of a module like require.resolve() but from a given path", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/resolve-from#readme", + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "license": "MIT", + "name": "resolve-from", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/resolve-from.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0" +} diff --git a/node_modules/resolve-from/readme.md b/node_modules/resolve-from/readme.md new file mode 100644 index 0000000..bb4ca91 --- /dev/null +++ b/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/saslprep/.editorconfig b/node_modules/saslprep/.editorconfig new file mode 100644 index 0000000..d1d8a41 --- /dev/null +++ b/node_modules/saslprep/.editorconfig @@ -0,0 +1,10 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/node_modules/saslprep/.eslintrc b/node_modules/saslprep/.eslintrc new file mode 100644 index 0000000..06c7684 --- /dev/null +++ b/node_modules/saslprep/.eslintrc @@ -0,0 +1,17 @@ +{ + "plugins": [ + "prettier" + ], + "env": { + "browser": true, + "node": true, + "es6": true + }, + "rules": { + "prettier/prettier": ["error", { + "semi": false, + "singleQuote": true, + "trailingComma": "es5" + }] + } +} diff --git a/node_modules/saslprep/.gitattributes b/node_modules/saslprep/.gitattributes new file mode 100644 index 0000000..3ba4536 --- /dev/null +++ b/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/node_modules/saslprep/.travis.yml b/node_modules/saslprep/.travis.yml new file mode 100644 index 0000000..53b824d --- /dev/null +++ b/node_modules/saslprep/.travis.yml @@ -0,0 +1,5 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" diff --git a/node_modules/saslprep/LICENSE b/node_modules/saslprep/LICENSE new file mode 100644 index 0000000..481c7a5 --- /dev/null +++ b/node_modules/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +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. \ No newline at end of file diff --git a/node_modules/saslprep/code-points.mem b/node_modules/saslprep/code-points.mem new file mode 100644 index 0000000000000000000000000000000000000000..4781b066802688bdf954d2e89bcfac967db29c09 GIT binary patch literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0) +const first = x => x[0] +const last = x => x[x.length - 1] + +/** + * SASLprep. + * @param {string} input + * @param {object} opts + * @param {boolean} opts.allowUnassigned + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.') + } + + if (input.length === 0) { + return '' + } + + // 1. Map + const mapped_input = input + .split('') + .map(getCodePoint) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)) + + // 2. Normalize + const normalized_input = String.fromCodePoint(...mapped_input).normalize('NFKC') + + const normalized_map = normalized_input.split('').map(getCodePoint) + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ) + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ) + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ) + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ) + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map + .some((character) => bidirectional_r_al.get(character)) + + const hasBidiL = normalized_map + .some((character) => bidirectional_l.get(character)) + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ) + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input))) + const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input))) + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ) + } + + return normalized_input +} diff --git a/node_modules/saslprep/lib/code-points.js b/node_modules/saslprep/lib/code-points.js new file mode 100644 index 0000000..4c5885a --- /dev/null +++ b/node_modules/saslprep/lib/code-points.js @@ -0,0 +1,996 @@ +'use strict' + +const { range } = require('./util') + +/** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ +const unassigned_code_points = new Set([ + 0x0221, + ...range(0x0234, 0x024F), + ...range(0x02AE, 0x02AF), + ...range(0x02EF, 0x02FF), + ...range(0x0350, 0x035F), + ...range(0x0370, 0x0373), + ...range(0x0376, 0x0379), + ...range(0x037B, 0x037D), + ...range(0x037F, 0x0383), + 0x038B, + 0x038D, + 0x03A2, + 0x03CF, + ...range(0x03F7, 0x03FF), + 0x0487, + 0x04CF, + ...range(0x04F6, 0x04F7), + ...range(0x04FA, 0x04FF), + ...range(0x0510, 0x0530), + ...range(0x0557, 0x0558), + 0x0560, + 0x0588, + ...range(0x058B, 0x0590), + 0x05A2, + 0x05BA, + ...range(0x05C5, 0x05CF), + ...range(0x05EB, 0x05EF), + ...range(0x05F5, 0x060B), + ...range(0x060D, 0x061A), + ...range(0x061C, 0x061E), + 0x0620, + ...range(0x063B, 0x063F), + ...range(0x0656, 0x065F), + ...range(0x06EE, 0x06EF), + 0x06FF, + 0x070E, + ...range(0x072D, 0x072F), + ...range(0x074B, 0x077F), + ...range(0x07B2, 0x0900), + 0x0904, + ...range(0x093A, 0x093B), + ...range(0x094E, 0x094F), + ...range(0x0955, 0x0957), + ...range(0x0971, 0x0980), + 0x0984, + ...range(0x098D, 0x098E), + ...range(0x0991, 0x0992), + 0x09A9, + 0x09B1, + ...range(0x09B3, 0x09B5), + ...range(0x09BA, 0x09BB), + 0x09BD, + ...range(0x09C5, 0x09C6), + ...range(0x09C9, 0x09CA), + ...range(0x09CE, 0x09D6), + ...range(0x09D8, 0x09DB), + 0x09DE, + ...range(0x09E4, 0x09E5), + ...range(0x09FB, 0x0A01), + ...range(0x0A03, 0x0A04), + ...range(0x0A0B, 0x0A0E), + ...range(0x0A11, 0x0A12), + 0x0A29, + 0x0A31, + 0x0A34, + 0x0A37, + ...range(0x0A3A, 0x0A3B), + 0x0A3D, + ...range(0x0A43, 0x0A46), + ...range(0x0A49, 0x0A4A), + ...range(0x0A4E, 0x0A58), + 0x0A5D, + ...range(0x0A5F, 0x0A65), + ...range(0x0A75, 0x0A80), + 0x0A84, + 0x0A8C, + 0x0A8E, + 0x0A92, + 0x0AA9, + 0x0AB1, + 0x0AB4, + ...range(0x0ABA, 0x0ABB), + 0x0AC6, + 0x0ACA, + ...range(0x0ACE, 0x0ACF), + ...range(0x0AD1, 0x0ADF), + ...range(0x0AE1, 0x0AE5), + ...range(0x0AF0, 0x0B00), + 0x0B04, + ...range(0x0B0D, 0x0B0E), + ...range(0x0B11, 0x0B12), + 0x0B29, + 0x0B31, + ...range(0x0B34, 0x0B35), + ...range(0x0B3A, 0x0B3B), + ...range(0x0B44, 0x0B46), + ...range(0x0B49, 0x0B4A), + ...range(0x0B4E, 0x0B55), + ...range(0x0B58, 0x0B5B), + 0x0B5E, + ...range(0x0B62, 0x0B65), + ...range(0x0B71, 0x0B81), + 0x0B84, + ...range(0x0B8B, 0x0B8D), + 0x0B91, + ...range(0x0B96, 0x0B98), + 0x0B9B, + 0x0B9D, + ...range(0x0BA0, 0x0BA2), + ...range(0x0BA5, 0x0BA7), + ...range(0x0BAB, 0x0BAD), + 0x0BB6, + ...range(0x0BBA, 0x0BBD), + ...range(0x0BC3, 0x0BC5), + 0x0BC9, + ...range(0x0BCE, 0x0BD6), + ...range(0x0BD8, 0x0BE6), + ...range(0x0BF3, 0x0C00), + 0x0C04, + 0x0C0D, + 0x0C11, + 0x0C29, + 0x0C34, + ...range(0x0C3A, 0x0C3D), + 0x0C45, + 0x0C49, + ...range(0x0C4E, 0x0C54), + ...range(0x0C57, 0x0C5F), + ...range(0x0C62, 0x0C65), + ...range(0x0C70, 0x0C81), + 0x0C84, + 0x0C8D, + 0x0C91, + 0x0CA9, + 0x0CB4, + ...range(0x0CBA, 0x0CBD), + 0x0CC5, + 0x0CC9, + ...range(0x0CCE, 0x0CD4), + ...range(0x0CD7, 0x0CDD), + 0x0CDF, + ...range(0x0CE2, 0x0CE5), + ...range(0x0CF0, 0x0D01), + 0x0D04, + 0x0D0D, + 0x0D11, + 0x0D29, + ...range(0x0D3A, 0x0D3D), + ...range(0x0D44, 0x0D45), + 0x0D49, + ...range(0x0D4E, 0x0D56), + ...range(0x0D58, 0x0D5F), + ...range(0x0D62, 0x0D65), + ...range(0x0D70, 0x0D81), + 0x0D84, + ...range(0x0D97, 0x0D99), + 0x0DB2, + 0x0DBC, + ...range(0x0DBE, 0x0DBF), + ...range(0x0DC7, 0x0DC9), + ...range(0x0DCB, 0x0DCE), + 0x0DD5, + 0x0DD7, + ...range(0x0DE0, 0x0DF1), + ...range(0x0DF5, 0x0E00), + ...range(0x0E3B, 0x0E3E), + ...range(0x0E5C, 0x0E80), + 0x0E83, + ...range(0x0E85, 0x0E86), + 0x0E89, + ...range(0x0E8B, 0x0E8C), + ...range(0x0E8E, 0x0E93), + 0x0E98, + 0x0EA0, + 0x0EA4, + 0x0EA6, + ...range(0x0EA8, 0x0EA9), + 0x0EAC, + 0x0EBA, + ...range(0x0EBE, 0x0EBF), + 0x0EC5, + 0x0EC7, + ...range(0x0ECE, 0x0ECF), + ...range(0x0EDA, 0x0EDB), + ...range(0x0EDE, 0x0EFF), + 0x0F48, + ...range(0x0F6B, 0x0F70), + ...range(0x0F8C, 0x0F8F), + 0x0F98, + 0x0FBD, + ...range(0x0FCD, 0x0FCE), + ...range(0x0FD0, 0x0FFF), + 0x1022, + 0x1028, + 0x102B, + ...range(0x1033, 0x1035), + ...range(0x103A, 0x103F), + ...range(0x105A, 0x109F), + ...range(0x10C6, 0x10CF), + ...range(0x10F9, 0x10FA), + ...range(0x10FC, 0x10FF), + ...range(0x115A, 0x115E), + ...range(0x11A3, 0x11A7), + ...range(0x11FA, 0x11FF), + 0x1207, + 0x1247, + 0x1249, + ...range(0x124E, 0x124F), + 0x1257, + 0x1259, + ...range(0x125E, 0x125F), + 0x1287, + 0x1289, + ...range(0x128E, 0x128F), + 0x12AF, + 0x12B1, + ...range(0x12B6, 0x12B7), + 0x12BF, + 0x12C1, + ...range(0x12C6, 0x12C7), + 0x12CF, + 0x12D7, + 0x12EF, + 0x130F, + 0x1311, + ...range(0x1316, 0x1317), + 0x131F, + 0x1347, + ...range(0x135B, 0x1360), + ...range(0x137D, 0x139F), + ...range(0x13F5, 0x1400), + ...range(0x1677, 0x167F), + ...range(0x169D, 0x169F), + ...range(0x16F1, 0x16FF), + 0x170D, + ...range(0x1715, 0x171F), + ...range(0x1737, 0x173F), + ...range(0x1754, 0x175F), + 0x176D, + 0x1771, + ...range(0x1774, 0x177F), + ...range(0x17DD, 0x17DF), + ...range(0x17EA, 0x17FF), + 0x180F, + ...range(0x181A, 0x181F), + ...range(0x1878, 0x187F), + ...range(0x18AA, 0x1DFF), + ...range(0x1E9C, 0x1E9F), + ...range(0x1EFA, 0x1EFF), + ...range(0x1F16, 0x1F17), + ...range(0x1F1E, 0x1F1F), + ...range(0x1F46, 0x1F47), + ...range(0x1F4E, 0x1F4F), + 0x1F58, + 0x1F5A, + 0x1F5C, + 0x1F5E, + ...range(0x1F7E, 0x1F7F), + 0x1FB5, + 0x1FC5, + ...range(0x1FD4, 0x1FD5), + 0x1FDC, + ...range(0x1FF0, 0x1FF1), + 0x1FF5, + 0x1FFF, + ...range(0x2053, 0x2056), + ...range(0x2058, 0x205E), + ...range(0x2064, 0x2069), + ...range(0x2072, 0x2073), + ...range(0x208F, 0x209F), + ...range(0x20B2, 0x20CF), + ...range(0x20EB, 0x20FF), + ...range(0x213B, 0x213C), + ...range(0x214C, 0x2152), + ...range(0x2184, 0x218F), + ...range(0x23CF, 0x23FF), + ...range(0x2427, 0x243F), + ...range(0x244B, 0x245F), + 0x24FF, + ...range(0x2614, 0x2615), + 0x2618, + ...range(0x267E, 0x267F), + ...range(0x268A, 0x2700), + 0x2705, + ...range(0x270A, 0x270B), + 0x2728, + 0x274C, + 0x274E, + ...range(0x2753, 0x2755), + 0x2757, + ...range(0x275F, 0x2760), + ...range(0x2795, 0x2797), + 0x27B0, + ...range(0x27BF, 0x27CF), + ...range(0x27EC, 0x27EF), + ...range(0x2B00, 0x2E7F), + 0x2E9A, + ...range(0x2EF4, 0x2EFF), + ...range(0x2FD6, 0x2FEF), + ...range(0x2FFC, 0x2FFF), + 0x3040, + ...range(0x3097, 0x3098), + ...range(0x3100, 0x3104), + ...range(0x312D, 0x3130), + 0x318F, + ...range(0x31B8, 0x31EF), + ...range(0x321D, 0x321F), + ...range(0x3244, 0x3250), + ...range(0x327C, 0x327E), + ...range(0x32CC, 0x32CF), + 0x32FF, + ...range(0x3377, 0x337A), + ...range(0x33DE, 0x33DF), + 0x33FF, + ...range(0x4DB6, 0x4DFF), + ...range(0x9FA6, 0x9FFF), + ...range(0xA48D, 0xA48F), + ...range(0xA4C7, 0xABFF), + ...range(0xD7A4, 0xD7FF), + ...range(0xFA2E, 0xFA2F), + ...range(0xFA6B, 0xFAFF), + ...range(0xFB07, 0xFB12), + ...range(0xFB18, 0xFB1C), + 0xFB37, + 0xFB3D, + 0xFB3F, + 0xFB42, + 0xFB45, + ...range(0xFBB2, 0xFBD2), + ...range(0xFD40, 0xFD4F), + ...range(0xFD90, 0xFD91), + ...range(0xFDC8, 0xFDCF), + ...range(0xFDFD, 0xFDFF), + ...range(0xFE10, 0xFE1F), + ...range(0xFE24, 0xFE2F), + ...range(0xFE47, 0xFE48), + 0xFE53, + 0xFE67, + ...range(0xFE6C, 0xFE6F), + 0xFE75, + ...range(0xFEFD, 0xFEFE), + 0xFF00, + ...range(0xFFBF, 0xFFC1), + ...range(0xFFC8, 0xFFC9), + ...range(0xFFD0, 0xFFD1), + ...range(0xFFD8, 0xFFD9), + ...range(0xFFDD, 0xFFDF), + 0xFFE7, + ...range(0xFFEF, 0xFFF8), + ...range(0x10000, 0x102FF), + 0x1031F, + ...range(0x10324, 0x1032F), + ...range(0x1034B, 0x103FF), + ...range(0x10426, 0x10427), + ...range(0x1044E, 0x1CFFF), + ...range(0x1D0F6, 0x1D0FF), + ...range(0x1D127, 0x1D129), + ...range(0x1D1DE, 0x1D3FF), + 0x1D455, + 0x1D49D, + ...range(0x1D4A0, 0x1D4A1), + ...range(0x1D4A3, 0x1D4A4), + ...range(0x1D4A7, 0x1D4A8), + 0x1D4AD, + 0x1D4BA, + 0x1D4BC, + 0x1D4C1, + 0x1D4C4, + 0x1D506, + ...range(0x1D50B, 0x1D50C), + 0x1D515, + 0x1D51D, + 0x1D53A, + 0x1D53F, + 0x1D545, + ...range(0x1D547, 0x1D549), + 0x1D551, + ...range(0x1D6A4, 0x1D6A7), + ...range(0x1D7CA, 0x1D7CD), + ...range(0x1D800, 0x1FFFD), + ...range(0x2A6D7, 0x2F7FF), + ...range(0x2FA1E, 0x2FFFD), + ...range(0x30000, 0x3FFFD), + ...range(0x40000, 0x4FFFD), + ...range(0x50000, 0x5FFFD), + ...range(0x60000, 0x6FFFD), + ...range(0x70000, 0x7FFFD), + ...range(0x80000, 0x8FFFD), + ...range(0x90000, 0x9FFFD), + ...range(0xA0000, 0xAFFFD), + ...range(0xB0000, 0xBFFFD), + ...range(0xC0000, 0xCFFFD), + ...range(0xD0000, 0xDFFFD), + 0xE0000, + ...range(0xE0002, 0xE001F), + ...range(0xE0080, 0xEFFFD), +]) + +/** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ +const commonly_mapped_to_nothing = new Set([ + 0x00AD, + 0x034F, + 0x1806, + 0x180B, + 0x180C, + 0x180D, + 0x200B, + 0x200C, + 0x200D, + 0x2060, + 0xFE00, + 0xFE01, + 0xFE02, + 0xFE03, + 0xFE04, + 0xFE05, + 0xFE06, + 0xFE07, + 0xFE08, + 0xFE09, + 0xFE0A, + 0xFE0B, + 0xFE0C, + 0xFE0D, + 0xFE0E, + 0xFE0F, + 0xFEFF, +]) + +/** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ +const non_ASCII_space_characters = new Set([ + 0x00a0 /* NO-BREAK SPACE */, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000 /* EN QUAD */, + 0x2001 /* EM QUAD */, + 0x2002 /* EN SPACE */, + 0x2003 /* EM SPACE */, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007 /* FIGURE SPACE */, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009 /* THIN SPACE */, + 0x200a /* HAIR SPACE */, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000 /* IDEOGRAPHIC SPACE */, +]) + +/** + * 2.3. Prohibited Output + * @type {Set} + */ +const prohibited_characters = new Set([ + ...non_ASCII_space_characters, + + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, + 0x007f /* DELETE */, + + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + ...range(0x0080, 0x009F), /* [CONTROL CHARACTERS] */ + 0x06DD, /* ARABIC END OF AYAH */ + 0x070F, /* SYRIAC ABBREVIATION MARK */ + 0x180E, /* MONGOLIAN VOWEL SEPARATOR */ + 0x200C, /* ZERO WIDTH NON-JOINER */ + 0x200D, /* ZERO WIDTH JOINER */ + 0x2028, /* LINE SEPARATOR */ + 0x2029, /* PARAGRAPH SEPARATOR */ + 0x2060, /* WORD JOINER */ + 0x2061, /* FUNCTION APPLICATION */ + 0x2062, /* INVISIBLE TIMES */ + 0x2063, /* INVISIBLE SEPARATOR */ + ...range(0x206A, 0x206F), /* [CONTROL CHARACTERS] */ + 0xFEFF, /* ZERO WIDTH NO-BREAK SPACE */ + ...range(0xFFF9, 0xFFFC), /* [CONTROL CHARACTERS] */ + ...range(0x1D173, 0x1D17A), /* [MUSICAL CONTROL CHARACTERS] */ + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + ...range(0xE000, 0xF8FF), /* [PRIVATE USE, PLANE 0] */ + ...range(0xF0000, 0xFFFFD), /* [PRIVATE USE, PLANE 15] */ + ...range(0x100000, 0x10FFFD), /* [PRIVATE USE, PLANE 16] */ + + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + ...range(0xFDD0, 0xFDEF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xFFFE, 0xFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x1FFFE, 0x1FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x2FFFE, 0x2FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x3FFFE, 0x3FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x4FFFE, 0x4FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x5FFFE, 0x5FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x6FFFE, 0x6FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x7FFFE, 0x7FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x8FFFE, 0x8FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x9FFFE, 0x9FFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xAFFFE, 0xAFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xBFFFE, 0xBFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xCFFFE, 0xCFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xDFFFE, 0xDFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0xEFFFE, 0xEFFFF), /* [NONCHARACTER CODE POINTS] */ + ...range(0x10FFFE, 0x10FFFF), /* [NONCHARACTER CODE POINTS] */ + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + ...range(0xD800, 0xDFFF), + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xFFF9, /* INTERLINEAR ANNOTATION ANCHOR */ + 0xFFFA, /* INTERLINEAR ANNOTATION SEPARATOR */ + 0xFFFB, /* INTERLINEAR ANNOTATION TERMINATOR */ + 0xFFFC, /* OBJECT REPLACEMENT CHARACTER */ + 0xFFFD, /* REPLACEMENT CHARACTER */ + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + ...range(0x2FF0, 0x2FFB), /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */ + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340, /* COMBINING GRAVE TONE MARK */ + 0x0341, /* COMBINING ACUTE TONE MARK */ + 0x200E, /* LEFT-TO-RIGHT MARK */ + 0x200F, /* RIGHT-TO-LEFT MARK */ + 0x202A, /* LEFT-TO-RIGHT EMBEDDING */ + 0x202B, /* RIGHT-TO-LEFT EMBEDDING */ + 0x202C, /* POP DIRECTIONAL FORMATTING */ + 0x202D, /* LEFT-TO-RIGHT OVERRIDE */ + 0x202E, /* RIGHT-TO-LEFT OVERRIDE */ + 0x206A, /* INHIBIT SYMMETRIC SWAPPING */ + 0x206B, /* ACTIVATE SYMMETRIC SWAPPING */ + 0x206C, /* INHIBIT ARABIC FORM SHAPING */ + 0x206D, /* ACTIVATE ARABIC FORM SHAPING */ + 0x206E, /* NATIONAL DIGIT SHAPES */ + 0x206F, /* NOMINAL DIGIT SHAPES */ + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xE0001, /* LANGUAGE TAG */ + ...range(0xE0020, 0xE007F) /* [TAGGING CHARACTERS] */ +]) + +/** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ +const bidirectional_r_al = new Set([ + 0x05BE, + 0x05C0, + 0x05C3, + ...range(0x05D0, 0x05EA), + ...range(0x05F0, 0x05F4), + 0x061B, + 0x061F, + ...range(0x0621, 0x063A), + ...range(0x0640, 0x064A), + ...range(0x066D, 0x066F), + ...range(0x0671, 0x06D5), + 0x06DD, + ...range(0x06E5, 0x06E6), + ...range(0x06FA, 0x06FE), + ...range(0x0700, 0x070D), + 0x0710, + ...range(0x0712, 0x072C), + ...range(0x0780, 0x07A5), + 0x07B1, + 0x200F, + 0xFB1D, + ...range(0xFB1F, 0xFB28), + ...range(0xFB2A, 0xFB36), + ...range(0xFB38, 0xFB3C), + 0xFB3E, + ...range(0xFB40, 0xFB41), + ...range(0xFB43, 0xFB44), + ...range(0xFB46, 0xFBB1), + ...range(0xFBD3, 0xFD3D), + ...range(0xFD50, 0xFD8F), + ...range(0xFD92, 0xFDC7), + ...range(0xFDF0, 0xFDFC), + ...range(0xFE70, 0xFE74), + ...range(0xFE76, 0xFEFC), +]) + +/** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ +const bidirectional_l = new Set([ + ...range(0x0041, 0x005A), + ...range(0x0061, 0x007A), + 0x00AA, + 0x00B5, + 0x00BA, + ...range(0x00C0, 0x00D6), + ...range(0x00D8, 0x00F6), + ...range(0x00F8, 0x0220), + ...range(0x0222, 0x0233), + ...range(0x0250, 0x02AD), + ...range(0x02B0, 0x02B8), + ...range(0x02BB, 0x02C1), + ...range(0x02D0, 0x02D1), + ...range(0x02E0, 0x02E4), + 0x02EE, + 0x037A, + 0x0386, + ...range(0x0388, 0x038A), + 0x038C, + ...range(0x038E, 0x03A1), + ...range(0x03A3, 0x03CE), + ...range(0x03D0, 0x03F5), + ...range(0x0400, 0x0482), + ...range(0x048A, 0x04CE), + ...range(0x04D0, 0x04F5), + ...range(0x04F8, 0x04F9), + ...range(0x0500, 0x050F), + ...range(0x0531, 0x0556), + ...range(0x0559, 0x055F), + ...range(0x0561, 0x0587), + 0x0589, + 0x0903, + ...range(0x0905, 0x0939), + ...range(0x093D, 0x0940), + ...range(0x0949, 0x094C), + 0x0950, + ...range(0x0958, 0x0961), + ...range(0x0964, 0x0970), + ...range(0x0982, 0x0983), + ...range(0x0985, 0x098C), + ...range(0x098F, 0x0990), + ...range(0x0993, 0x09A8), + ...range(0x09AA, 0x09B0), + 0x09B2, + ...range(0x09B6, 0x09B9), + ...range(0x09BE, 0x09C0), + ...range(0x09C7, 0x09C8), + ...range(0x09CB, 0x09CC), + 0x09D7, + ...range(0x09DC, 0x09DD), + ...range(0x09DF, 0x09E1), + ...range(0x09E6, 0x09F1), + ...range(0x09F4, 0x09FA), + ...range(0x0A05, 0x0A0A), + ...range(0x0A0F, 0x0A10), + ...range(0x0A13, 0x0A28), + ...range(0x0A2A, 0x0A30), + ...range(0x0A32, 0x0A33), + ...range(0x0A35, 0x0A36), + ...range(0x0A38, 0x0A39), + ...range(0x0A3E, 0x0A40), + ...range(0x0A59, 0x0A5C), + 0x0A5E, + ...range(0x0A66, 0x0A6F), + ...range(0x0A72, 0x0A74), + 0x0A83, + ...range(0x0A85, 0x0A8B), + 0x0A8D, + ...range(0x0A8F, 0x0A91), + ...range(0x0A93, 0x0AA8), + ...range(0x0AAA, 0x0AB0), + ...range(0x0AB2, 0x0AB3), + ...range(0x0AB5, 0x0AB9), + ...range(0x0ABD, 0x0AC0), + 0x0AC9, + ...range(0x0ACB, 0x0ACC), + 0x0AD0, + 0x0AE0, + ...range(0x0AE6, 0x0AEF), + ...range(0x0B02, 0x0B03), + ...range(0x0B05, 0x0B0C), + ...range(0x0B0F, 0x0B10), + ...range(0x0B13, 0x0B28), + ...range(0x0B2A, 0x0B30), + ...range(0x0B32, 0x0B33), + ...range(0x0B36, 0x0B39), + ...range(0x0B3D, 0x0B3E), + 0x0B40, + ...range(0x0B47, 0x0B48), + ...range(0x0B4B, 0x0B4C), + 0x0B57, + ...range(0x0B5C, 0x0B5D), + ...range(0x0B5F, 0x0B61), + ...range(0x0B66, 0x0B70), + 0x0B83, + ...range(0x0B85, 0x0B8A), + ...range(0x0B8E, 0x0B90), + ...range(0x0B92, 0x0B95), + ...range(0x0B99, 0x0B9A), + 0x0B9C, + ...range(0x0B9E, 0x0B9F), + ...range(0x0BA3, 0x0BA4), + ...range(0x0BA8, 0x0BAA), + ...range(0x0BAE, 0x0BB5), + ...range(0x0BB7, 0x0BB9), + ...range(0x0BBE, 0x0BBF), + ...range(0x0BC1, 0x0BC2), + ...range(0x0BC6, 0x0BC8), + ...range(0x0BCA, 0x0BCC), + 0x0BD7, + ...range(0x0BE7, 0x0BF2), + ...range(0x0C01, 0x0C03), + ...range(0x0C05, 0x0C0C), + ...range(0x0C0E, 0x0C10), + ...range(0x0C12, 0x0C28), + ...range(0x0C2A, 0x0C33), + ...range(0x0C35, 0x0C39), + ...range(0x0C41, 0x0C44), + ...range(0x0C60, 0x0C61), + ...range(0x0C66, 0x0C6F), + ...range(0x0C82, 0x0C83), + ...range(0x0C85, 0x0C8C), + ...range(0x0C8E, 0x0C90), + ...range(0x0C92, 0x0CA8), + ...range(0x0CAA, 0x0CB3), + ...range(0x0CB5, 0x0CB9), + 0x0CBE, + ...range(0x0CC0, 0x0CC4), + ...range(0x0CC7, 0x0CC8), + ...range(0x0CCA, 0x0CCB), + ...range(0x0CD5, 0x0CD6), + 0x0CDE, + ...range(0x0CE0, 0x0CE1), + ...range(0x0CE6, 0x0CEF), + ...range(0x0D02, 0x0D03), + ...range(0x0D05, 0x0D0C), + ...range(0x0D0E, 0x0D10), + ...range(0x0D12, 0x0D28), + ...range(0x0D2A, 0x0D39), + ...range(0x0D3E, 0x0D40), + ...range(0x0D46, 0x0D48), + ...range(0x0D4A, 0x0D4C), + 0x0D57, + ...range(0x0D60, 0x0D61), + ...range(0x0D66, 0x0D6F), + ...range(0x0D82, 0x0D83), + ...range(0x0D85, 0x0D96), + ...range(0x0D9A, 0x0DB1), + ...range(0x0DB3, 0x0DBB), + 0x0DBD, + ...range(0x0DC0, 0x0DC6), + ...range(0x0DCF, 0x0DD1), + ...range(0x0DD8, 0x0DDF), + ...range(0x0DF2, 0x0DF4), + ...range(0x0E01, 0x0E30), + ...range(0x0E32, 0x0E33), + ...range(0x0E40, 0x0E46), + ...range(0x0E4F, 0x0E5B), + ...range(0x0E81, 0x0E82), + 0x0E84, + ...range(0x0E87, 0x0E88), + 0x0E8A, + 0x0E8D, + ...range(0x0E94, 0x0E97), + ...range(0x0E99, 0x0E9F), + ...range(0x0EA1, 0x0EA3), + 0x0EA5, + 0x0EA7, + ...range(0x0EAA, 0x0EAB), + ...range(0x0EAD, 0x0EB0), + ...range(0x0EB2, 0x0EB3), + 0x0EBD, + ...range(0x0EC0, 0x0EC4), + 0x0EC6, + ...range(0x0ED0, 0x0ED9), + ...range(0x0EDC, 0x0EDD), + ...range(0x0F00, 0x0F17), + ...range(0x0F1A, 0x0F34), + 0x0F36, + 0x0F38, + ...range(0x0F3E, 0x0F47), + ...range(0x0F49, 0x0F6A), + 0x0F7F, + 0x0F85, + ...range(0x0F88, 0x0F8B), + ...range(0x0FBE, 0x0FC5), + ...range(0x0FC7, 0x0FCC), + 0x0FCF, + ...range(0x1000, 0x1021), + ...range(0x1023, 0x1027), + ...range(0x1029, 0x102A), + 0x102C, + 0x1031, + 0x1038, + ...range(0x1040, 0x1057), + ...range(0x10A0, 0x10C5), + ...range(0x10D0, 0x10F8), + 0x10FB, + ...range(0x1100, 0x1159), + ...range(0x115F, 0x11A2), + ...range(0x11A8, 0x11F9), + ...range(0x1200, 0x1206), + ...range(0x1208, 0x1246), + 0x1248, + ...range(0x124A, 0x124D), + ...range(0x1250, 0x1256), + 0x1258, + ...range(0x125A, 0x125D), + ...range(0x1260, 0x1286), + 0x1288, + ...range(0x128A, 0x128D), + ...range(0x1290, 0x12AE), + 0x12B0, + ...range(0x12B2, 0x12B5), + ...range(0x12B8, 0x12BE), + 0x12C0, + ...range(0x12C2, 0x12C5), + ...range(0x12C8, 0x12CE), + ...range(0x12D0, 0x12D6), + ...range(0x12D8, 0x12EE), + ...range(0x12F0, 0x130E), + 0x1310, + ...range(0x1312, 0x1315), + ...range(0x1318, 0x131E), + ...range(0x1320, 0x1346), + ...range(0x1348, 0x135A), + ...range(0x1361, 0x137C), + ...range(0x13A0, 0x13F4), + ...range(0x1401, 0x1676), + ...range(0x1681, 0x169A), + ...range(0x16A0, 0x16F0), + ...range(0x1700, 0x170C), + ...range(0x170E, 0x1711), + ...range(0x1720, 0x1731), + ...range(0x1735, 0x1736), + ...range(0x1740, 0x1751), + ...range(0x1760, 0x176C), + ...range(0x176E, 0x1770), + ...range(0x1780, 0x17B6), + ...range(0x17BE, 0x17C5), + ...range(0x17C7, 0x17C8), + ...range(0x17D4, 0x17DA), + 0x17DC, + ...range(0x17E0, 0x17E9), + ...range(0x1810, 0x1819), + ...range(0x1820, 0x1877), + ...range(0x1880, 0x18A8), + ...range(0x1E00, 0x1E9B), + ...range(0x1EA0, 0x1EF9), + ...range(0x1F00, 0x1F15), + ...range(0x1F18, 0x1F1D), + ...range(0x1F20, 0x1F45), + ...range(0x1F48, 0x1F4D), + ...range(0x1F50, 0x1F57), + 0x1F59, + 0x1F5B, + 0x1F5D, + ...range(0x1F5F, 0x1F7D), + ...range(0x1F80, 0x1FB4), + ...range(0x1FB6, 0x1FBC), + 0x1FBE, + ...range(0x1FC2, 0x1FC4), + ...range(0x1FC6, 0x1FCC), + ...range(0x1FD0, 0x1FD3), + ...range(0x1FD6, 0x1FDB), + ...range(0x1FE0, 0x1FEC), + ...range(0x1FF2, 0x1FF4), + ...range(0x1FF6, 0x1FFC), + 0x200E, + 0x2071, + 0x207F, + 0x2102, + 0x2107, + ...range(0x210A, 0x2113), + 0x2115, + ...range(0x2119, 0x211D), + 0x2124, + 0x2126, + 0x2128, + ...range(0x212A, 0x212D), + ...range(0x212F, 0x2131), + ...range(0x2133, 0x2139), + ...range(0x213D, 0x213F), + ...range(0x2145, 0x2149), + ...range(0x2160, 0x2183), + ...range(0x2336, 0x237A), + 0x2395, + ...range(0x249C, 0x24E9), + ...range(0x3005, 0x3007), + ...range(0x3021, 0x3029), + ...range(0x3031, 0x3035), + ...range(0x3038, 0x303C), + ...range(0x3041, 0x3096), + ...range(0x309D, 0x309F), + ...range(0x30A1, 0x30FA), + ...range(0x30FC, 0x30FF), + ...range(0x3105, 0x312C), + ...range(0x3131, 0x318E), + ...range(0x3190, 0x31B7), + ...range(0x31F0, 0x321C), + ...range(0x3220, 0x3243), + ...range(0x3260, 0x327B), + ...range(0x327F, 0x32B0), + ...range(0x32C0, 0x32CB), + ...range(0x32D0, 0x32FE), + ...range(0x3300, 0x3376), + ...range(0x337B, 0x33DD), + ...range(0x33E0, 0x33FE), + ...range(0x3400, 0x4DB5), + ...range(0x4E00, 0x9FA5), + ...range(0xA000, 0xA48C), + ...range(0xAC00, 0xD7A3), + ...range(0xD800, 0xFA2D), + ...range(0xFA30, 0xFA6A), + ...range(0xFB00, 0xFB06), + ...range(0xFB13, 0xFB17), + ...range(0xFF21, 0xFF3A), + ...range(0xFF41, 0xFF5A), + ...range(0xFF66, 0xFFBE), + ...range(0xFFC2, 0xFFC7), + ...range(0xFFCA, 0xFFCF), + ...range(0xFFD2, 0xFFD7), + ...range(0xFFDA, 0xFFDC), + ...range(0x10300, 0x1031E), + ...range(0x10320, 0x10323), + ...range(0x10330, 0x1034A), + ...range(0x10400, 0x10425), + ...range(0x10428, 0x1044D), + ...range(0x1D000, 0x1D0F5), + ...range(0x1D100, 0x1D126), + ...range(0x1D12A, 0x1D166), + ...range(0x1D16A, 0x1D172), + ...range(0x1D183, 0x1D184), + ...range(0x1D18C, 0x1D1A9), + ...range(0x1D1AE, 0x1D1DD), + ...range(0x1D400, 0x1D454), + ...range(0x1D456, 0x1D49C), + ...range(0x1D49E, 0x1D49F), + 0x1D4A2, + ...range(0x1D4A5, 0x1D4A6), + ...range(0x1D4A9, 0x1D4AC), + ...range(0x1D4AE, 0x1D4B9), + 0x1D4BB, + ...range(0x1D4BD, 0x1D4C0), + ...range(0x1D4C2, 0x1D4C3), + ...range(0x1D4C5, 0x1D505), + ...range(0x1D507, 0x1D50A), + ...range(0x1D50D, 0x1D514), + ...range(0x1D516, 0x1D51C), + ...range(0x1D51E, 0x1D539), + ...range(0x1D53B, 0x1D53E), + ...range(0x1D540, 0x1D544), + 0x1D546, + ...range(0x1D54A, 0x1D550), + ...range(0x1D552, 0x1D6A3), + ...range(0x1D6A8, 0x1D7C9), + ...range(0x20000, 0x2A6D6), + ...range(0x2F800, 0x2FA1D), + ...range(0xF0000, 0xFFFFD), + ...range(0x100000, 0x10FFFD) +]) + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l +} diff --git a/node_modules/saslprep/lib/memory-code-points.js b/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 0000000..c776d42 --- /dev/null +++ b/node_modules/saslprep/lib/memory-code-points.js @@ -0,0 +1,34 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const bitfield = require('sparse-bitfield'); + +const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); +let offset = 0; + +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +} diff --git a/node_modules/saslprep/lib/util.js b/node_modules/saslprep/lib/util.js new file mode 100644 index 0000000..697e0d0 --- /dev/null +++ b/node_modules/saslprep/lib/util.js @@ -0,0 +1,15 @@ +'use strict' + +function range(from, to) { + // TODO: make this inlined. + const list = new Array(to - from + 1) + + for(let i = 0; i < list.length; ++i) { + list[i] = from + i + } + return list +} + +module.exports = { + range +} diff --git a/node_modules/saslprep/package.json b/node_modules/saslprep/package.json new file mode 100644 index 0000000..9d93de0 --- /dev/null +++ b/node_modules/saslprep/package.json @@ -0,0 +1,66 @@ +{ + "_from": "saslprep@^1.0.0", + "_id": "saslprep@1.0.2", + "_inBundle": false, + "_integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==", + "_location": "/saslprep", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "saslprep@^1.0.0", + "name": "saslprep", + "escapedName": "saslprep", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/mongodb-core" + ], + "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.2.tgz", + "_shasum": "da5ab936e6ea0bbae911ffec77534be370c9f52d", + "_spec": "saslprep@^1.0.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\mongodb-core", + "author": { + "name": "Dmitry Tsvettsikh", + "email": "me@reklatsmasters.com" + }, + "bugs": { + "url": "https://github.com/reklatsmasters/saslprep/issues" + }, + "bundleDependencies": false, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "deprecated": false, + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", + "devDependencies": { + "ava": "^0.25.0", + "eslint-plugin-prettier": "^2.1.2", + "prettier": "^1.4.4" + }, + "engines": { + "node": ">=6" + }, + "homepage": "https://github.com/reklatsmasters/saslprep#readme", + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "license": "MIT", + "main": "index.js", + "name": "saslprep", + "repository": { + "type": "git", + "url": "git+https://github.com/reklatsmasters/saslprep.git" + }, + "scripts": { + "gen-code-points": "node generate-code-points.js > code-points.mem", + "test": "ava" + }, + "version": "1.0.2" +} diff --git a/node_modules/saslprep/readme.md b/node_modules/saslprep/readme.md new file mode 100644 index 0000000..a94e760 --- /dev/null +++ b/node_modules/saslprep/readme.md @@ -0,0 +1,31 @@ +# saslprep +[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) +[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) +[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('saslprep') + +saslprep('password\u00AD') // password +saslprep('password\u0007') // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017 (c) Dmitriy Tsvettsikh diff --git a/node_modules/saslprep/test/index.js b/node_modules/saslprep/test/index.js new file mode 100644 index 0000000..1fb71cf --- /dev/null +++ b/node_modules/saslprep/test/index.js @@ -0,0 +1,70 @@ +import test from 'ava' +import saslprep from '../' + +const chr = String.fromCodePoint + +test('should work with liatin letters', (t) => { + const str = 'user' + t.is(saslprep(str), str) +}) + +test('should work be case preserved', (t) => { + const str = 'USER' + t.is(saslprep(str), str) +}) + +test('should remove `mapped to nothing` characters', (t) => { + t.is(saslprep('I\u00ADX'), 'IX') +}) + +test('should replace `Non-ASCII space characters` with space', (t) => { + t.is(saslprep('a\u00A0b'), 'a\u0020b') +}) + +test('should normalize as NFKC', (t) => { + t.is(saslprep('\u00AA'), 'a') + t.is(saslprep('\u2168'), 'IX') +}) + +test('should throws when prohibited characters', (t) => { + // C.2.1 ASCII control characters + t.throws(() => saslprep('a\u007Fb')) + + // C.2.2 Non-ASCII control characters + t.throws(() => saslprep('a\u06DDb')) + + // C.3 Private use + t.throws(() => saslprep('a\uE000b')) + + // C.4 Non-character code points + t.throws(() => saslprep(`a${chr(0x1FFFE)}b`)) + + // C.5 Surrogate codes + t.throws(() => saslprep('a\uD800b')) + + // C.6 Inappropriate for plain text + t.throws(() => saslprep('a\uFFF9b')) + + // C.7 Inappropriate for canonical representation + t.throws(() => saslprep('a\u2FF0b')) + + // C.8 Change display properties or are deprecated + t.throws(() => saslprep('a\u200Eb')) + + // C.9 Tagging characters + t.throws(() => saslprep(`a${chr(0xE0001)}b`)) +}) + +test('should not containt RandALCat and LCat bidi', (t) => { + t.throws(() => saslprep('a\u06DD\u00AAb')) +}) + +test('RandALCat should be first and last', (t) => { + t.notThrows(() => saslprep('\u0627\u0031\u0628')) + t.throws(() => saslprep('\u0627\u0031')) +}) + +test('should handle unassigned code points', (t) => { + t.throws(() => saslprep('a\u0487')) + t.notThrows(() => saslprep('a\u0487', {allowUnassigned: true})) +}) diff --git a/node_modules/saslprep/test/util.js b/node_modules/saslprep/test/util.js new file mode 100644 index 0000000..fb39a85 --- /dev/null +++ b/node_modules/saslprep/test/util.js @@ -0,0 +1,15 @@ +import { setFlagsFromString } from 'v8' +import { range } from '../lib/util' +import test from 'ava' + +// 984 by default. +setFlagsFromString('--stack_size=500') + +test('should work', (t) => { + const list = range(1, 3) + t.deepEqual(list, [1, 2, 3]) +}) + +test('should work for large ranges', (t) => { + t.notThrows(() => range(1, 1e6)) +}) diff --git a/node_modules/semver/LICENSE b/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/semver/README.md b/node_modules/semver/README.md new file mode 100644 index 0000000..e0edbb7 --- /dev/null +++ b/node_modules/semver/README.md @@ -0,0 +1,399 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the http://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver +string to semver. It looks for the first digit in a string, and +consumes all remaining characters which satisfy at least a partial semver +(e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). +Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). +All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). +Only text which lacks digits will fail coercion (`version one` is not valid). +The maximum length for any semver component considered for coercion is 16 characters; +longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). +The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; +higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/node_modules/semver/bin/semver b/node_modules/semver/bin/semver new file mode 100644 index 0000000..9100ed4 --- /dev/null +++ b/node_modules/semver/bin/semver @@ -0,0 +1,153 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + , versions = [] + , range = [] + , gt = [] + , lt = [] + , eq = [] + , inc = null + , version = require("../package.json").version + , loose = false + , includePrerelease = false + , coerce = false + , identifier = undefined + , semver = require("../semver") + , reverse = false + , options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var i = a.indexOf('=') + if (i !== -1) { + a = a.slice(0, i) + argv.unshift(a.slice(i + 1)) + } + switch (a) { + case "-rv": case "-rev": case "--rev": case "--reverse": + reverse = true + break + case "-l": case "--loose": + loose = true + break + case "-p": case "--include-prerelease": + includePrerelease = true + break + case "-v": case "--version": + versions.push(argv.shift()) + break + case "-i": case "--inc": case "--increment": + switch (argv[0]) { + case "major": case "minor": case "patch": case "prerelease": + case "premajor": case "preminor": case "prepatch": + inc = argv.shift() + break + default: + inc = "patch" + break + } + break + case "--preid": + identifier = argv.shift() + break + case "-r": case "--range": + range.push(argv.shift()) + break + case "-c": case "--coerce": + coerce = true + break + case "-h": case "--help": case "-?": + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || {version: v}).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) + return failInc() + + for (var i = 0, l = range.length; i < l ; i ++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error("--inc can only be used on a single version with no range") + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? "rcompare" : "compare" + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v,i,_) { console.log(v) }) +} + +function help () { + console.log(["SemVer " + version + ,"" + ,"A JavaScript implementation of the http://semver.org/ specification" + ,"Copyright Isaac Z. Schlueter" + ,"" + ,"Usage: semver [options] [ [...]]" + ,"Prints valid versions sorted by SemVer precedence" + ,"" + ,"Options:" + ,"-r --range " + ," Print versions that match the specified range." + ,"" + ,"-i --increment []" + ," Increment a version by the specified level. Level can" + ," be one of: major, minor, patch, premajor, preminor," + ," prepatch, or prerelease. Default level is 'patch'." + ," Only one version may be specified." + ,"" + ,"--preid " + ," Identifier to be used to prefix premajor, preminor," + ," prepatch or prerelease version increments." + ,"" + ,"-l --loose" + ," Interpret versions and ranges loosely" + ,"" + ,"-p --include-prerelease" + ," Always include prerelease versions in range matching" + ,"" + ,"-c --coerce" + ," Coerce a string into SemVer if possible" + ," (does not imply --loose)" + ,"" + ,"Program exits successfully if any valid version satisfies" + ,"all supplied ranges, and prints all satisfying versions." + ,"" + ,"If no satisfying versions are found, then exits failure." + ,"" + ,"Versions are printed in ascending order, so supplying" + ,"multiple versions to the utility will just sort them." + ].join("\n")) +} diff --git a/node_modules/semver/package.json b/node_modules/semver/package.json new file mode 100644 index 0000000..d97046c --- /dev/null +++ b/node_modules/semver/package.json @@ -0,0 +1,54 @@ +{ + "_from": "semver@^5.1.0", + "_id": "semver@5.6.0", + "_inBundle": false, + "_integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", + "_location": "/semver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "semver@^5.1.0", + "name": "semver", + "escapedName": "semver", + "rawSpec": "^5.1.0", + "saveSpec": null, + "fetchSpec": "^5.1.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "_shasum": "7e74256fbaa49c75aa7c7a205cc22799cac80004", + "_spec": "semver@^5.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\require_optional", + "bin": { + "semver": "./bin/semver" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^12.0.1" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "semver.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "test": "tap test/*.js --cov -J" + }, + "version": "5.6.0" +} diff --git a/node_modules/semver/range.bnf b/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/semver/semver.js b/node_modules/semver/semver.js new file mode 100644 index 0000000..0cc5735 --- /dev/null +++ b/node_modules/semver/semver.js @@ -0,0 +1,1352 @@ +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++; +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, options) { + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = options.loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, options); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, options) { + var v = parse(version, options); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, options) { + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + if (version instanceof SemVer) { + if (version.loose === options.loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, options); + + debug('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.options, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.options); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.options); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.options); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, options) { + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, options); + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.options.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.options); + + return cmp(version, this.operator, this.semver, this.options); +}; + +Comparator.prototype.intersects = function(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options); + return satisfies(this.value, rangeTmp, options); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options); + return satisfies(comp.semver, rangeTmp, options); + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')); + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')); + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + + +exports.Range = Range; +function Range(range, options) { + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range(range.raw, options); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options); + } + + if (!(this instanceof Range)) + return new Range(range, options); + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.options.loose; + range = range.trim(); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, this.options); + }, this).join(' ').split(/\s+/); + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, this.options); + }, this); + + return set; +}; + +Range.prototype.intersects = function(range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function(thisComparators) { + return thisComparators.every(function(thisComparator) { + return range.set.some(function(rangeComparators) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, options) { + return new Range(range, options).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, options) { + debug('comp', comp, options); + comp = replaceCarets(comp, options); + debug('caret', comp); + comp = replaceTildes(comp, options); + debug('tildes', comp); + comp = replaceXRanges(comp, options); + debug('xrange', comp); + comp = replaceStars(comp, options); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, options); + }).join(' '); +} + +function replaceTilde(comp, options) { + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + var r = options.loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, options); + }).join(' '); +} + +function replaceCaret(comp, options) { + debug('caret', comp, options); + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + var r = options.loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, options) { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, options); + }).join(' '); +} + +function replaceXRange(comp, options) { + comp = comp.trim(); + if (!options || typeof options !== 'object') + options = { loose: !!options, includePrerelease: false } + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, options) { + debug('replaceStars', comp, options); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.options); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) + return true; + } + return false; +}; + +function testSet(set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (!options) + options = {} + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, options) { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) + max = v; + maxSV = new SemVer(max, options); + } + } + }) + return max; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { // compare(min, v, true) + min = v; + minSV = new SemVer(min, options); + } + } + }) + return min; +} + +exports.validRange = validRange; +function validRange(range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, options) { + return outside(version, range, '<', options); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, options) { + return outside(version, range, '>', options); +} + +exports.outside = outside; +function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range(range, options); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, options) { + var parsed = parse(version, options); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} + +exports.intersects = intersects; +function intersects(r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce; +function coerce(version) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + var match = version.match(re[COERCE]); + + if (match == null) + return null; + + return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); +} diff --git a/node_modules/express/node_modules/send/.npmignore b/node_modules/send/.npmignore similarity index 100% rename from node_modules/express/node_modules/send/.npmignore rename to node_modules/send/.npmignore diff --git a/node_modules/express/node_modules/send/History.md b/node_modules/send/History.md similarity index 100% rename from node_modules/express/node_modules/send/History.md rename to node_modules/send/History.md diff --git a/node_modules/express/node_modules/send/Readme.md b/node_modules/send/Readme.md similarity index 100% rename from node_modules/express/node_modules/send/Readme.md rename to node_modules/send/Readme.md diff --git a/node_modules/express/node_modules/send/index.js b/node_modules/send/index.js similarity index 100% rename from node_modules/express/node_modules/send/index.js rename to node_modules/send/index.js diff --git a/node_modules/express/node_modules/send/lib/send.js b/node_modules/send/lib/send.js similarity index 100% rename from node_modules/express/node_modules/send/lib/send.js rename to node_modules/send/lib/send.js diff --git a/node_modules/express/node_modules/send/lib/utils.js b/node_modules/send/lib/utils.js similarity index 100% rename from node_modules/express/node_modules/send/lib/utils.js rename to node_modules/send/lib/utils.js diff --git a/node_modules/send/node_modules/debug/.jshintrc b/node_modules/send/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/node_modules/send/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/node_modules/send/node_modules/debug/.npmignore b/node_modules/send/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/node_modules/send/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/node_modules/send/node_modules/debug/History.md b/node_modules/send/node_modules/debug/History.md new file mode 100644 index 0000000..42139a8 --- /dev/null +++ b/node_modules/send/node_modules/debug/History.md @@ -0,0 +1,126 @@ + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/node_modules/debug/Makefile b/node_modules/send/node_modules/debug/Makefile new file mode 100644 index 0000000..b0bde6e --- /dev/null +++ b/node_modules/send/node_modules/debug/Makefile @@ -0,0 +1,33 @@ + +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# applications +NODE ?= $(shell which node) +NPM ?= $(NODE) $(shell which npm) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +all: dist/debug.js + +install: node_modules + +clean: + @rm -rf node_modules dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean diff --git a/node_modules/send/node_modules/debug/Readme.md b/node_modules/send/node_modules/debug/Readme.md new file mode 100644 index 0000000..e3607db --- /dev/null +++ b/node_modules/send/node_modules/debug/Readme.md @@ -0,0 +1,153 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, and the Firebug plugin for Firefox. + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + +### stderr vs stdout + +You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: + +Example _stderr.js_: + +```js +var debug = require('../'); +var log = debug('app:log'); + +// by default console.log is used +log('goes to stdout!'); + +var error = debug('app:error'); +// set this namespace to log via console.error +error.log = console.error.bind(console); // don't forget to bind to console! +error('goes to stderr'); +log('still goes to stdout!'); + +// set all output to go via console.warn +// overrides all per-namespace log settings +debug.log = console.warn.bind(console); +log('now goes to stderr via console.warn'); +error('still goes to stderr, but via console.warn now'); +``` + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + +## License + +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> + +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. diff --git a/node_modules/send/node_modules/debug/browser.js b/node_modules/send/node_modules/debug/browser.js new file mode 100644 index 0000000..41d957c --- /dev/null +++ b/node_modules/send/node_modules/debug/browser.js @@ -0,0 +1,144 @@ + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors and the Firebug + * extension (*not* the built-in Firefox web inpector) are + * known to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // is webkit? http://stackoverflow.com/a/16459606/376773 + return ('WebkitAppearance' in document.documentElement.style) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (window.console && (console.firebug || (console.exception && console.table))); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + return JSON.stringify(v); +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? '%c ' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return args + + var c = 'color: ' + this.color; + args = [args[0], c, ''].concat(Array.prototype.slice.call(args, 1)); + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + return args; +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // This hackery is required for IE8, + // where the `console.log` function doesn't have 'apply' + return 'object' == typeof console + && 'function' == typeof console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + localStorage.removeItem('debug'); + } else { + localStorage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = localStorage.debug; + } catch(e) {} + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); diff --git a/node_modules/send/node_modules/debug/component.json b/node_modules/send/node_modules/debug/component.json new file mode 100644 index 0000000..dfb0311 --- /dev/null +++ b/node_modules/send/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "1.0.2", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "browser.js", + "scripts": [ + "browser.js", + "debug.js" + ], + "dependencies": { + "guille/ms.js": "0.6.1" + } +} diff --git a/node_modules/send/node_modules/debug/debug.js b/node_modules/send/node_modules/debug/debug.js new file mode 100644 index 0000000..c514fb7 --- /dev/null +++ b/node_modules/send/node_modules/debug/debug.js @@ -0,0 +1,197 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = debug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lowercased letter, i.e. "n". + */ + +exports.formatters = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function selectColor() { + return exports.colors[prevColor++ % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function debug(namespace) { + + // define the `disabled` version + function disabled() { + } + disabled.enabled = false; + + // define the `enabled` version + function enabled() { + + var self = enabled; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // add the `color` if not set + if (null == self.useColors) self.useColors = exports.useColors(); + if (null == self.color && self.useColors) self.color = selectColor(); + + var args = Array.prototype.slice.call(arguments); + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %o + args = ['%o'].concat(args); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + if ('function' === typeof exports.formatArgs) { + args = exports.formatArgs.apply(self, args); + } + var logFn = exports.log || enabled.log || console.log.bind(console); + logFn.apply(self, args); + } + enabled.enabled = true; + + var fn = exports.enabled(namespace) ? enabled : disabled; + + fn.namespace = namespace; + + return fn; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + var split = (namespaces || '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace('*', '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/send/node_modules/debug/node.js b/node_modules/send/node_modules/debug/node.js new file mode 100644 index 0000000..c94f7d1 --- /dev/null +++ b/node_modules/send/node_modules/debug/node.js @@ -0,0 +1,129 @@ + +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); + if (0 === debugColors.length) { + return tty.isatty(1); + } else { + return '0' !== debugColors + && 'no' !== debugColors + && 'false' !== debugColors + && 'disabled' !== debugColors; + } +} + +/** + * Map %o to `util.inspect()`, since Node doesn't do that out of the box. + */ + +var inspect = (4 === util.inspect.length ? + // node <= 0.8.x + function (v, colors) { + return util.inspect(v, void 0, void 0, colors); + } : + // node > 0.8.x + function (v, colors) { + return util.inspect(v, { colors: colors }); + } +); + +exports.formatters.o = function(v) { + return inspect(v, this.useColors) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + var name = this.namespace; + + if (useColors) { + var c = this.color; + + args[0] = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[0m' + + args[0] + '\u001b[3' + c + 'm' + + ' +' + exports.humanize(this.diff) + '\u001b[0m'; + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } + return args; +} + +/** + * Invokes `console.log()` with the specified arguments. + */ + +function log() { + return console.log.apply(console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/send/node_modules/debug/package.json b/node_modules/send/node_modules/debug/package.json new file mode 100644 index 0000000..0551644 --- /dev/null +++ b/node_modules/send/node_modules/debug/package.json @@ -0,0 +1,69 @@ +{ + "_from": "debug@1.0.2", + "_id": "debug@1.0.2", + "_inBundle": false, + "_integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", + "_location": "/send/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@1.0.2", + "name": "debug", + "escapedName": "debug", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/send" + ], + "_resolved": "http://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "_shasum": "3849591c10cce648476c3c7c2e2e3416db5963c4", + "_spec": "debug@1.0.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\send", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + } + ], + "dependencies": { + "ms": "0.6.2" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "4.1.6", + "mocha": "*" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "./node.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "1.0.2" +} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/.npmignore b/node_modules/send/node_modules/ms/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/.npmignore rename to node_modules/send/node_modules/ms/.npmignore diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/README.md b/node_modules/send/node_modules/ms/README.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/README.md rename to node_modules/send/node_modules/ms/README.md diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/index.js b/node_modules/send/node_modules/ms/index.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/index.js rename to node_modules/send/node_modules/ms/index.js diff --git a/node_modules/express/node_modules/debug/node_modules/ms/package.json b/node_modules/send/node_modules/ms/package.json similarity index 55% rename from node_modules/express/node_modules/debug/node_modules/ms/package.json rename to node_modules/send/node_modules/ms/package.json index 8334411..25cdd43 100644 --- a/node_modules/express/node_modules/debug/node_modules/ms/package.json +++ b/node_modules/send/node_modules/ms/package.json @@ -1,43 +1,67 @@ { - "name": "ms", - "version": "0.6.2", - "description": "Tiny ms conversion utility", - "repository": { - "type": "git", - "url": "git://github.com/guille/ms.js.git" + "_from": "ms@0.6.2", + "_id": "ms@0.6.2", + "_inBundle": false, + "_integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=", + "_location": "/send/ms", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" }, - "main": "./index", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" + "_npmVersion": "1.2.30", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.6.2", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.6.2", + "saveSpec": null, + "fetchSpec": "0.6.2" }, + "_requiredBy": [ + "/send", + "/send/debug" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", + "_spec": "ms@0.6.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\send", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "ms/index.js": "index.js" } }, - "bugs": { - "url": "https://github.com/guille/ms.js/issues" + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" }, - "_id": "ms@0.6.2", + "directories": {}, "dist": { "shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", "tarball": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz" }, - "_from": "ms@0.6.2", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, + "homepage": "https://github.com/guille/ms.js#readme", + "main": "./index", "maintainers": [ { "name": "rauchg", "email": "rauchg@gmail.com" } ], - "directories": {}, - "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz" + "name": "ms", + "repository": { + "type": "git", + "url": "git://github.com/guille/ms.js.git" + }, + "scripts": {}, + "version": "0.6.2" } diff --git a/node_modules/express/node_modules/send/package.json b/node_modules/send/package.json similarity index 75% rename from node_modules/express/node_modules/send/package.json rename to node_modules/send/package.json index 44a3252..5972cb0 100644 --- a/node_modules/express/node_modules/send/package.json +++ b/node_modules/send/package.json @@ -1,27 +1,46 @@ { - "name": "send", - "description": "Better streaming static file server with Range and conditional-GET support", - "version": "0.5.0", + "_from": "send@0.5.0", + "_id": "send@0.5.0", + "_inBundle": false, + "_integrity": "sha1-/A9+L5Limuv9ihst60o5TnpTGmg=", + "_location": "/send", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "send@0.5.0", + "name": "send", + "escapedName": "send", + "rawSpec": "0.5.0", + "saveSpec": null, + "fetchSpec": "0.5.0" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/send/-/send-0.5.0.tgz", + "_shasum": "fc0f7e2f92e29aebfd8a1b2deb4a394e7a531a68", + "_spec": "send@0.5.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, + "bugs": { + "url": "https://github.com/visionmedia/send/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" } ], - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/send" - }, - "keywords": [ - "static", - "file", - "server" - ], "dependencies": { "debug": "1.0.2", "escape-html": "1.0.1", @@ -31,35 +50,29 @@ "ms": "0.6.2", "range-parser": "~1.0.0" }, + "deprecated": false, + "description": "Better streaming static file server with Range and conditional-GET support", "devDependencies": { "istanbul": "0.2.10", "mocha": "~1.20.0", "should": "~4.0.0", "supertest": "~0.13.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec" - }, - "bugs": { - "url": "https://github.com/visionmedia/send/issues" - }, - "homepage": "https://github.com/visionmedia/send", - "_id": "send@0.5.0", + "directories": {}, "dist": { "shasum": "fc0f7e2f92e29aebfd8a1b2deb4a394e7a531a68", "tarball": "http://registry.npmjs.org/send/-/send-0.5.0.tgz" }, - "_from": "send@0.5.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/visionmedia/send", + "keywords": [ + "static", + "file", + "server" + ], + "license": "MIT", "maintainers": [ { "name": "tjholowaychuk", @@ -70,7 +83,15 @@ "email": "doug@somethingdoug.com" } ], - "directories": {}, - "_shasum": "fc0f7e2f92e29aebfd8a1b2deb4a394e7a531a68", - "_resolved": "https://registry.npmjs.org/send/-/send-0.5.0.tgz" + "name": "send", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/send.git" + }, + "scripts": { + "test": "mocha --reporter dot", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec" + }, + "version": "0.5.0" } diff --git a/node_modules/express/node_modules/serve-static/.npmignore b/node_modules/serve-static/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/.npmignore rename to node_modules/serve-static/.npmignore diff --git a/node_modules/express/node_modules/serve-static/History.md b/node_modules/serve-static/History.md similarity index 100% rename from node_modules/express/node_modules/serve-static/History.md rename to node_modules/serve-static/History.md diff --git a/node_modules/express/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE similarity index 100% rename from node_modules/express/node_modules/serve-static/LICENSE rename to node_modules/serve-static/LICENSE diff --git a/node_modules/express/node_modules/serve-static/Readme.md b/node_modules/serve-static/Readme.md similarity index 100% rename from node_modules/express/node_modules/serve-static/Readme.md rename to node_modules/serve-static/Readme.md diff --git a/node_modules/express/node_modules/serve-static/index.js b/node_modules/serve-static/index.js similarity index 100% rename from node_modules/express/node_modules/serve-static/index.js rename to node_modules/serve-static/index.js diff --git a/node_modules/serve-static/node_modules/debug/.jshintrc b/node_modules/serve-static/node_modules/debug/.jshintrc new file mode 100644 index 0000000..299877f --- /dev/null +++ b/node_modules/serve-static/node_modules/debug/.jshintrc @@ -0,0 +1,3 @@ +{ + "laxbreak": true +} diff --git a/node_modules/serve-static/node_modules/debug/.npmignore b/node_modules/serve-static/node_modules/debug/.npmignore new file mode 100644 index 0000000..7e6163d --- /dev/null +++ b/node_modules/serve-static/node_modules/debug/.npmignore @@ -0,0 +1,6 @@ +support +test +examples +example +*.sock +dist diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/History.md b/node_modules/serve-static/node_modules/debug/History.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/History.md rename to node_modules/serve-static/node_modules/debug/History.md diff --git a/node_modules/serve-static/node_modules/debug/Makefile b/node_modules/serve-static/node_modules/debug/Makefile new file mode 100644 index 0000000..b0bde6e --- /dev/null +++ b/node_modules/serve-static/node_modules/debug/Makefile @@ -0,0 +1,33 @@ + +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# applications +NODE ?= $(shell which node) +NPM ?= $(NODE) $(shell which npm) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +all: dist/debug.js + +install: node_modules + +clean: + @rm -rf node_modules dist + +dist: + @mkdir -p $@ + +dist/debug.js: node_modules browser.js debug.js dist + @$(BROWSERIFY) \ + --standalone debug \ + . > $@ + +node_modules: package.json + @NODE_ENV= $(NPM) install + @touch node_modules + +.PHONY: all install clean diff --git a/node_modules/serve-static/node_modules/debug/Readme.md b/node_modules/serve-static/node_modules/debug/Readme.md new file mode 100644 index 0000000..e3607db --- /dev/null +++ b/node_modules/serve-static/node_modules/debug/Readme.md @@ -0,0 +1,153 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, and the Firebug plugin for Firefox. + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + +### stderr vs stdout + +You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: + +Example _stderr.js_: + +```js +var debug = require('../'); +var log = debug('app:log'); + +// by default console.log is used +log('goes to stdout!'); + +var error = debug('app:error'); +// set this namespace to log via console.error +error.log = console.error.bind(console); // don't forget to bind to console! +error('goes to stderr'); +log('still goes to stdout!'); + +// set all output to go via console.warn +// overrides all per-namespace log settings +debug.log = console.warn.bind(console); +log('now goes to stderr via console.warn'); +error('still goes to stderr, but via console.warn now'); +``` + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + +## License + +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> + +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. diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/browser.js b/node_modules/serve-static/node_modules/debug/browser.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/browser.js rename to node_modules/serve-static/node_modules/debug/browser.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/component.json b/node_modules/serve-static/node_modules/debug/component.json similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/component.json rename to node_modules/serve-static/node_modules/debug/component.json diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/debug.js b/node_modules/serve-static/node_modules/debug/debug.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/debug.js rename to node_modules/serve-static/node_modules/debug/debug.js diff --git a/node_modules/serve-static/node_modules/debug/node.js b/node_modules/serve-static/node_modules/debug/node.js new file mode 100644 index 0000000..c94f7d1 --- /dev/null +++ b/node_modules/serve-static/node_modules/debug/node.js @@ -0,0 +1,129 @@ + +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); + if (0 === debugColors.length) { + return tty.isatty(1); + } else { + return '0' !== debugColors + && 'no' !== debugColors + && 'false' !== debugColors + && 'disabled' !== debugColors; + } +} + +/** + * Map %o to `util.inspect()`, since Node doesn't do that out of the box. + */ + +var inspect = (4 === util.inspect.length ? + // node <= 0.8.x + function (v, colors) { + return util.inspect(v, void 0, void 0, colors); + } : + // node > 0.8.x + function (v, colors) { + return util.inspect(v, { colors: colors }); + } +); + +exports.formatters.o = function(v) { + return inspect(v, this.useColors) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs() { + var args = arguments; + var useColors = this.useColors; + var name = this.namespace; + + if (useColors) { + var c = this.color; + + args[0] = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[0m' + + args[0] + '\u001b[3' + c + 'm' + + ' +' + exports.humanize(this.diff) + '\u001b[0m'; + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } + return args; +} + +/** + * Invokes `console.log()` with the specified arguments. + */ + +function log() { + return console.log.apply(console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/package.json b/node_modules/serve-static/node_modules/debug/package.json similarity index 69% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/package.json rename to node_modules/serve-static/node_modules/debug/package.json index de7d0d9..39d7d20 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/debug/package.json +++ b/node_modules/serve-static/node_modules/debug/package.json @@ -1,20 +1,47 @@ { - "name": "debug", - "version": "1.0.3", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" + "_from": "debug@1.0.3", + "_id": "debug@1.0.3", + "_inBundle": false, + "_integrity": "sha1-/IxrLWACgEtAgcAgjg9kYLofo+Q=", + "_location": "/serve-static/debug", + "_npmUser": { + "name": "tootallnate", + "email": "nathan@tootallnate.net" }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" + "_npmVersion": "1.4.14", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@1.0.3", + "name": "debug", + "escapedName": "debug", + "rawSpec": "1.0.3", + "saveSpec": null, + "fetchSpec": "1.0.3" + }, + "_requiredBy": [ + "/serve-static/send" ], + "_resolved": "http://registry.npmjs.org/debug/-/debug-1.0.3.tgz", + "_shasum": "fc8c6b2d6002804b4081c0208e0f6460ba1fa3e4", + "_spec": "debug@1.0.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\serve-static\\node_modules\\send", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, "contributors": [ { "name": "Nathan Rajlich", @@ -25,32 +52,25 @@ "dependencies": { "ms": "0.6.2" }, + "deprecated": false, + "description": "small debugging utility", "devDependencies": { "browserify": "4.1.6", "mocha": "*" }, - "main": "./node.js", - "browser": "./browser.js", - "component": { - "scripts": { - "debug/index.js": "browser.js", - "debug/debug.js": "debug.js" - } + "directories": {}, + "dist": { + "shasum": "fc8c6b2d6002804b4081c0208e0f6460ba1fa3e4", + "tarball": "http://registry.npmjs.org/debug/-/debug-1.0.3.tgz" }, "gitHead": "93c759961d53ad7f06a1892a8dd0bf4be4a7b9df", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@1.0.3", - "scripts": {}, - "_shasum": "fc8c6b2d6002804b4081c0208e0f6460ba1fa3e4", - "_from": "debug@1.0.3", - "_npmVersion": "1.4.14", - "_npmUser": { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "./node.js", "maintainers": [ { "name": "tjholowaychuk", @@ -61,10 +81,11 @@ "email": "nathan@tootallnate.net" } ], - "dist": { - "shasum": "fc8c6b2d6002804b4081c0208e0f6460ba1fa3e4", - "tarball": "http://registry.npmjs.org/debug/-/debug-1.0.3.tgz" + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/debug/-/debug-1.0.3.tgz" + "scripts": {}, + "version": "1.0.3" } diff --git a/node_modules/serve-static/node_modules/ms/.npmignore b/node_modules/serve-static/node_modules/ms/.npmignore new file mode 100644 index 0000000..d1aa0ce --- /dev/null +++ b/node_modules/serve-static/node_modules/ms/.npmignore @@ -0,0 +1,5 @@ +node_modules +test +History.md +Makefile +component.json diff --git a/node_modules/serve-static/node_modules/ms/README.md b/node_modules/serve-static/node_modules/ms/README.md new file mode 100644 index 0000000..d4ab12a --- /dev/null +++ b/node_modules/serve-static/node_modules/ms/README.md @@ -0,0 +1,33 @@ +# ms.js: miliseconds conversion utility + +```js +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('100') // 100 +``` + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours', { long: true })) // "10 hours" +``` + +- Node/Browser compatible. Published as `ms` in NPM. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as +a number (e.g: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of +equivalent ms is returned. + +## License + +MIT \ No newline at end of file diff --git a/node_modules/serve-static/node_modules/ms/index.js b/node_modules/serve-static/node_modules/ms/index.js new file mode 100644 index 0000000..c5847f8 --- /dev/null +++ b/node_modules/serve-static/node_modules/ms/index.js @@ -0,0 +1,111 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/package.json b/node_modules/serve-static/node_modules/ms/package.json similarity index 54% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/package.json rename to node_modules/serve-static/node_modules/ms/package.json index 0839b59..3895ee5 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/ms/package.json +++ b/node_modules/serve-static/node_modules/ms/package.json @@ -1,45 +1,66 @@ { - "name": "ms", - "version": "0.6.2", - "description": "Tiny ms conversion utility", - "repository": { - "type": "git", - "url": "git://github.com/guille/ms.js.git" + "_from": "ms@0.6.2", + "_id": "ms@0.6.2", + "_inBundle": false, + "_integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=", + "_location": "/serve-static/ms", + "_npmUser": { + "name": "rauchg", + "email": "rauchg@gmail.com" }, - "main": "./index", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" + "_npmVersion": "1.2.30", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@0.6.2", + "name": "ms", + "escapedName": "ms", + "rawSpec": "0.6.2", + "saveSpec": null, + "fetchSpec": "0.6.2" }, + "_requiredBy": [ + "/serve-static/debug", + "/serve-static/send" + ], + "_resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", + "_spec": "ms@0.6.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\serve-static\\node_modules\\send", + "bugs": { + "url": "https://github.com/guille/ms.js/issues" + }, + "bundleDependencies": false, "component": { "scripts": { "ms/index.js": "index.js" } }, - "bugs": { - "url": "https://github.com/guille/ms.js/issues" + "deprecated": false, + "description": "Tiny ms conversion utility", + "devDependencies": { + "expect.js": "*", + "mocha": "*", + "serve": "*" }, - "_id": "ms@0.6.2", + "directories": {}, "dist": { "shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", "tarball": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz" }, - "_from": "ms@0.6.2", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, + "homepage": "https://github.com/guille/ms.js", + "main": "./index", "maintainers": [ { "name": "rauchg", "email": "rauchg@gmail.com" } ], - "directories": {}, - "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "readme": "ERROR: No README data found!", - "homepage": "https://github.com/guille/ms.js" + "name": "ms", + "repository": { + "type": "git", + "url": "git://github.com/guille/ms.js.git" + }, + "version": "0.6.2" } diff --git a/node_modules/express/node_modules/serve-static/node_modules/parseurl/.npmignore b/node_modules/serve-static/node_modules/parseurl/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/parseurl/.npmignore rename to node_modules/serve-static/node_modules/parseurl/.npmignore diff --git a/node_modules/express/node_modules/serve-static/node_modules/parseurl/HISTORY.md b/node_modules/serve-static/node_modules/parseurl/HISTORY.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/parseurl/HISTORY.md rename to node_modules/serve-static/node_modules/parseurl/HISTORY.md diff --git a/node_modules/express/node_modules/serve-static/node_modules/parseurl/README.md b/node_modules/serve-static/node_modules/parseurl/README.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/parseurl/README.md rename to node_modules/serve-static/node_modules/parseurl/README.md diff --git a/node_modules/express/node_modules/serve-static/node_modules/parseurl/index.js b/node_modules/serve-static/node_modules/parseurl/index.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/parseurl/index.js rename to node_modules/serve-static/node_modules/parseurl/index.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/parseurl/package.json b/node_modules/serve-static/node_modules/parseurl/package.json similarity index 66% rename from node_modules/express/node_modules/serve-static/node_modules/parseurl/package.json rename to node_modules/serve-static/node_modules/parseurl/package.json index ab56844..6231f25 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/parseurl/package.json +++ b/node_modules/serve-static/node_modules/parseurl/package.json @@ -1,33 +1,51 @@ { - "name": "parseurl", - "description": "parse a url with memoization", - "version": "1.1.3", + "_from": "parseurl@~1.1.3", + "_id": "parseurl@1.1.3", + "_inBundle": false, + "_integrity": "sha1-HwBXOKxxtBe8LQhFy9+iqLY+pjk=", + "_location": "/serve-static/parseurl", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "parseurl@~1.1.3", + "name": "parseurl", + "escapedName": "parseurl", + "rawSpec": "~1.1.3", + "saveSpec": null, + "fetchSpec": "~1.1.3" + }, + "_requiredBy": [ + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz", + "_shasum": "1f005738ac71b417bc2d0845cbdfa2a8b63ea639", + "_spec": "parseurl@~1.1.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\serve-static", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, - "repository": { - "type": "git", - "url": "https://github.com/expressjs/parseurl.git" - }, "bugs": { "url": "https://github.com/expressjs/parseurl/issues", "email": "me@jongleberry.com" }, - "license": "MIT", - "homepage": "https://github.com/expressjs/parseurl", - "_id": "parseurl@1.1.3", + "bundleDependencies": false, + "deprecated": false, + "description": "parse a url with memoization", + "directories": {}, "dist": { "shasum": "1f005738ac71b417bc2d0845cbdfa2a8b63ea639", "tarball": "http://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz" }, - "_from": "parseurl@>=1.1.3 <1.2.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" - }, + "homepage": "https://github.com/expressjs/parseurl", + "license": "MIT", "maintainers": [ { "name": "jongleberry", @@ -54,7 +72,10 @@ "email": "fishrock123@rocketmail.com" } ], - "directories": {}, - "_shasum": "1f005738ac71b417bc2d0845cbdfa2a8b63ea639", - "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz" + "name": "parseurl", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/parseurl.git" + }, + "version": "1.1.3" } diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/.npmignore b/node_modules/serve-static/node_modules/send/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/.npmignore rename to node_modules/serve-static/node_modules/send/.npmignore diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/History.md b/node_modules/serve-static/node_modules/send/History.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/History.md rename to node_modules/serve-static/node_modules/send/History.md diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/Readme.md b/node_modules/serve-static/node_modules/send/Readme.md similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/Readme.md rename to node_modules/serve-static/node_modules/send/Readme.md diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/index.js b/node_modules/serve-static/node_modules/send/index.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/index.js rename to node_modules/serve-static/node_modules/send/index.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/lib/send.js b/node_modules/serve-static/node_modules/send/lib/send.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/lib/send.js rename to node_modules/serve-static/node_modules/send/lib/send.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/lib/utils.js b/node_modules/serve-static/node_modules/send/lib/utils.js similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/lib/utils.js rename to node_modules/serve-static/node_modules/send/lib/utils.js diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/package.json b/node_modules/serve-static/node_modules/send/package.json similarity index 74% rename from node_modules/express/node_modules/serve-static/node_modules/send/package.json rename to node_modules/serve-static/node_modules/send/package.json index 12bf94d..e4571ad 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/package.json +++ b/node_modules/serve-static/node_modules/send/package.json @@ -1,27 +1,46 @@ { - "name": "send", - "description": "Better streaming static file server with Range and conditional-GET support", - "version": "0.6.0", + "_from": "send@0.6.0", + "_id": "send@0.6.0", + "_inBundle": false, + "_integrity": "sha1-pZ2pJl23w1FB4Qec8fNo7g1Zs6s=", + "_location": "/serve-static/send", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "send@0.6.0", + "name": "send", + "escapedName": "send", + "rawSpec": "0.6.0", + "saveSpec": null, + "fetchSpec": "0.6.0" + }, + "_requiredBy": [ + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/send/-/send-0.6.0.tgz", + "_shasum": "a59da9265db7c35141e1079cf1f368ee0d59b3ab", + "_spec": "send@0.6.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\serve-static", "author": { "name": "TJ Holowaychuk", "email": "tj@vision-media.ca" }, + "bugs": { + "url": "https://github.com/visionmedia/send/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" } ], - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/send" - }, - "keywords": [ - "static", - "file", - "server" - ], "dependencies": { "debug": "1.0.3", "depd": "0.3.0", @@ -32,35 +51,29 @@ "ms": "0.6.2", "range-parser": "~1.0.0" }, + "deprecated": false, + "description": "Better streaming static file server with Range and conditional-GET support", "devDependencies": { "istanbul": "0.3.0", "mocha": "~1.20.0", "should": "~4.0.0", "supertest": "~0.13.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec" - }, - "bugs": { - "url": "https://github.com/visionmedia/send/issues" - }, - "homepage": "https://github.com/visionmedia/send", - "_id": "send@0.6.0", + "directories": {}, "dist": { "shasum": "a59da9265db7c35141e1079cf1f368ee0d59b3ab", "tarball": "http://registry.npmjs.org/send/-/send-0.6.0.tgz" }, - "_from": "send@0.6.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/visionmedia/send", + "keywords": [ + "static", + "file", + "server" + ], + "license": "MIT", "maintainers": [ { "name": "tjholowaychuk", @@ -71,7 +84,15 @@ "email": "doug@somethingdoug.com" } ], - "directories": {}, - "_shasum": "a59da9265db7c35141e1079cf1f368ee0d59b3ab", - "_resolved": "https://registry.npmjs.org/send/-/send-0.6.0.tgz" + "name": "send", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/send.git" + }, + "scripts": { + "test": "mocha --reporter dot", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec" + }, + "version": "0.6.0" } diff --git a/node_modules/express/node_modules/serve-static/package.json b/node_modules/serve-static/package.json similarity index 69% rename from node_modules/express/node_modules/serve-static/package.json rename to node_modules/serve-static/package.json index 02ab9a3..c0d9a7a 100644 --- a/node_modules/express/node_modules/serve-static/package.json +++ b/node_modules/serve-static/package.json @@ -1,50 +1,70 @@ { - "name": "serve-static", - "description": "Serve static files", - "version": "1.3.2", + "_from": "serve-static@~1.3.0", + "_id": "serve-static@1.3.2", + "_inBundle": false, + "_integrity": "sha1-2QSmy/VfURx4E49vRe5uadnRBco=", + "_location": "/serve-static", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": { + "depd": "0.3.0", + "escape-html": "1.0.1", + "finished": "1.2.2", + "fresh": "0.2.2", + "mime": "1.2.11", + "range-parser": "1.0.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "serve-static@~1.3.0", + "name": "serve-static", + "escapedName": "serve-static", + "rawSpec": "~1.3.0", + "saveSpec": null, + "fetchSpec": "~1.3.0" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz", + "_shasum": "d904a6cbf55f511c78138f6f45ee6e69d9d105ca", + "_spec": "serve-static@~1.3.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/expressjs/serve-static" + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" }, + "bundleDependencies": false, "dependencies": { "escape-html": "1.0.1", "parseurl": "~1.1.3", "send": "0.6.0" }, + "deprecated": false, + "description": "Serve static files", "devDependencies": { "istanbul": "0.3.0", "mocha": "~1.20.0", "should": "~4.0.0", "supertest": "~0.13.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot --require should test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" - }, - "bugs": { - "url": "https://github.com/expressjs/serve-static/issues" - }, - "homepage": "https://github.com/expressjs/serve-static", - "_id": "serve-static@1.3.2", + "directories": {}, "dist": { "shasum": "d904a6cbf55f511c78138f6f45ee6e69d9d105ca", "tarball": "http://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz" }, - "_from": "serve-static@>=1.3.0 <1.4.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/serve-static", + "license": "MIT", "maintainers": [ { "name": "dougwilson", @@ -71,7 +91,15 @@ "email": "fishrock123@rocketmail.com" } ], - "directories": {}, - "_shasum": "d904a6cbf55f511c78138f6f45ee6e69d9d105ca", - "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz" + "name": "serve-static", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/serve-static.git" + }, + "scripts": { + "test": "mocha --reporter dot --require should test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --require should test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --require should test/" + }, + "version": "1.3.2" } diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/.npmignore b/node_modules/sparse-bitfield/.npmignore similarity index 54% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/.npmignore rename to node_modules/sparse-bitfield/.npmignore index 72921ab..3c3629e 100644 --- a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/node_modules/ee-first/.npmignore +++ b/node_modules/sparse-bitfield/.npmignore @@ -1,2 +1 @@ -.DS_Store* node_modules diff --git a/node_modules/sparse-bitfield/.travis.yml b/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 0000000..c042821 --- /dev/null +++ b/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE b/node_modules/sparse-bitfield/LICENSE similarity index 95% rename from node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE rename to node_modules/sparse-bitfield/LICENSE index a7ae8ee..bae9da7 100644 --- a/node_modules/express/node_modules/type-is/node_modules/mime-types/LICENSE +++ b/node_modules/sparse-bitfield/LICENSE @@ -1,7 +1,6 @@ - The MIT License (MIT) -Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Mathias Buus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/node_modules/sparse-bitfield/README.md b/node_modules/sparse-bitfield/README.md new file mode 100644 index 0000000..7b6b8f9 --- /dev/null +++ b/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/node_modules/sparse-bitfield/index.js b/node_modules/sparse-bitfield/index.js new file mode 100644 index 0000000..ff458c9 --- /dev/null +++ b/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/node_modules/sparse-bitfield/package.json b/node_modules/sparse-bitfield/package.json new file mode 100644 index 0000000..3568746 --- /dev/null +++ b/node_modules/sparse-bitfield/package.json @@ -0,0 +1,55 @@ +{ + "_from": "sparse-bitfield@^3.0.3", + "_id": "sparse-bitfield@3.0.3", + "_inBundle": false, + "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "_location": "/sparse-bitfield", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "sparse-bitfield@^3.0.3", + "name": "sparse-bitfield", + "escapedName": "sparse-bitfield", + "rawSpec": "^3.0.3", + "saveSpec": null, + "fetchSpec": "^3.0.3" + }, + "_requiredBy": [ + "/saslprep" + ], + "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", + "_spec": "sparse-bitfield@^3.0.3", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\saslprep", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "bundleDependencies": false, + "dependencies": { + "memory-pager": "^1.0.2" + }, + "deprecated": false, + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield", + "license": "MIT", + "main": "index.js", + "name": "sparse-bitfield", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/sparse-bitfield.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "3.0.3" +} diff --git a/node_modules/sparse-bitfield/test.js b/node_modules/sparse-bitfield/test.js new file mode 100644 index 0000000..ae42ef4 --- /dev/null +++ b/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/.npmignore b/node_modules/type-is/.npmignore similarity index 100% rename from node_modules/express/node_modules/serve-static/node_modules/send/node_modules/finished/.npmignore rename to node_modules/type-is/.npmignore diff --git a/node_modules/express/node_modules/type-is/HISTORY.md b/node_modules/type-is/HISTORY.md similarity index 100% rename from node_modules/express/node_modules/type-is/HISTORY.md rename to node_modules/type-is/HISTORY.md diff --git a/node_modules/express/node_modules/type-is/README.md b/node_modules/type-is/README.md similarity index 100% rename from node_modules/express/node_modules/type-is/README.md rename to node_modules/type-is/README.md diff --git a/node_modules/express/node_modules/type-is/index.js b/node_modules/type-is/index.js similarity index 100% rename from node_modules/express/node_modules/type-is/index.js rename to node_modules/type-is/index.js diff --git a/node_modules/express/node_modules/type-is/package.json b/node_modules/type-is/package.json similarity index 75% rename from node_modules/express/node_modules/type-is/package.json rename to node_modules/type-is/package.json index 40d1159..201a661 100644 --- a/node_modules/express/node_modules/type-is/package.json +++ b/node_modules/type-is/package.json @@ -1,53 +1,69 @@ { - "name": "type-is", - "description": "Infer the content-type of a request.", - "version": "1.3.2", + "_from": "type-is@~1.3.2", + "_id": "type-is@1.3.2", + "_inBundle": false, + "_integrity": "sha1-TypdxYd1yhYwJQr8cYb4s2MJ0bs=", + "_location": "/type-is", + "_npmUser": { + "name": "jongleberry", + "email": "jonathanrichardong@gmail.com" + }, + "_npmVersion": "1.4.16", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "type-is@~1.3.2", + "name": "type-is", + "escapedName": "type-is", + "rawSpec": "~1.3.2", + "saveSpec": null, + "fetchSpec": "~1.3.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz", + "_shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", + "_spec": "type-is@~1.3.2", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Jonathan Ong", "email": "me@jongleberry.com", "url": "http://jongleberry.com" }, + "bugs": { + "url": "https://github.com/expressjs/type-is/issues" + }, + "bundleDependencies": false, "contributors": [ { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" } ], - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/expressjs/type-is" - }, "dependencies": { "media-typer": "0.2.0", "mime-types": "~1.0.1" }, + "deprecated": false, + "description": "Infer the content-type of a request.", "devDependencies": { "istanbul": "0.2.11", "mocha": "*", "should": "*" }, + "directories": {}, + "dist": { + "shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", + "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz" + }, "engines": { "node": ">= 0.8" }, - "scripts": { - "test": "mocha --require should --reporter spec --check-leaks --bail test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, "gitHead": "d76790909638d4cf1785e09858db5576f91f710f", - "bugs": { - "url": "https://github.com/expressjs/type-is/issues" - }, "homepage": "https://github.com/expressjs/type-is", - "_id": "type-is@1.3.2", - "_shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", - "_from": "type-is@>=1.3.2 <1.4.0", - "_npmVersion": "1.4.16", - "_npmUser": { - "name": "jongleberry", - "email": "jonathanrichardong@gmail.com" - }, + "license": "MIT", "maintainers": [ { "name": "jongleberry", @@ -74,10 +90,15 @@ "email": "fishrock123@rocketmail.com" } ], - "dist": { - "shasum": "4f2a5dc58775ca1630250afc7186f8b36309d1bb", - "tarball": "http://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz" + "name": "type-is", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/type-is.git" }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz" + "scripts": { + "test": "mocha --require should --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.3.2" } diff --git a/node_modules/express/node_modules/utils-merge/.travis.yml b/node_modules/utils-merge/.travis.yml similarity index 100% rename from node_modules/express/node_modules/utils-merge/.travis.yml rename to node_modules/utils-merge/.travis.yml diff --git a/node_modules/express/node_modules/utils-merge/LICENSE b/node_modules/utils-merge/LICENSE similarity index 100% rename from node_modules/express/node_modules/utils-merge/LICENSE rename to node_modules/utils-merge/LICENSE diff --git a/node_modules/express/node_modules/utils-merge/README.md b/node_modules/utils-merge/README.md similarity index 100% rename from node_modules/express/node_modules/utils-merge/README.md rename to node_modules/utils-merge/README.md diff --git a/node_modules/express/node_modules/utils-merge/index.js b/node_modules/utils-merge/index.js similarity index 100% rename from node_modules/express/node_modules/utils-merge/index.js rename to node_modules/utils-merge/index.js diff --git a/node_modules/express/node_modules/utils-merge/package.json b/node_modules/utils-merge/package.json similarity index 61% rename from node_modules/express/node_modules/utils-merge/package.json rename to node_modules/utils-merge/package.json index 7c115b0..5104702 100644 --- a/node_modules/express/node_modules/utils-merge/package.json +++ b/node_modules/utils-merge/package.json @@ -1,58 +1,80 @@ { - "name": "utils-merge", - "version": "1.0.0", - "description": "merge() utility function", - "keywords": [ - "util" - ], - "repository": { - "type": "git", - "url": "git://github.com/jaredhanson/utils-merge.git" + "_from": "utils-merge@1.0.0", + "_id": "utils-merge@1.0.0", + "_inBundle": false, + "_integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=", + "_location": "/utils-merge", + "_npmUser": { + "name": "jaredhanson", + "email": "jaredhanson@gmail.com" }, - "bugs": { - "url": "http://github.com/jaredhanson/utils-merge/issues" + "_npmVersion": "1.2.25", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "utils-merge@1.0.0", + "name": "utils-merge", + "escapedName": "utils-merge", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", + "_shasum": "0294fb922bb9375153541c4f7096231f287c8af8", + "_spec": "utils-merge@1.0.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Jared Hanson", "email": "jaredhanson@gmail.com", "url": "http://www.jaredhanson.net/" }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/MIT" - } - ], - "main": "./index", + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "bundleDependencies": false, "dependencies": {}, + "deprecated": false, + "description": "merge() utility function", "devDependencies": { - "mocha": "1.x.x", - "chai": "1.x.x" - }, - "scripts": { - "test": "node_modules/.bin/mocha --reporter spec --require test/bootstrap/node test/*.test.js" + "chai": "1.x.x", + "mocha": "1.x.x" }, - "engines": { - "node": ">= 0.4.0" - }, - "_id": "utils-merge@1.0.0", + "directories": {}, "dist": { "shasum": "0294fb922bb9375153541c4f7096231f287c8af8", "tarball": "http://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz" }, - "_from": "utils-merge@1.0.0", - "_npmVersion": "1.2.25", - "_npmUser": { - "name": "jaredhanson", - "email": "jaredhanson@gmail.com" + "engines": { + "node": ">= 0.4.0" }, + "homepage": "https://github.com/jaredhanson/utils-merge#readme", + "keywords": [ + "util" + ], + "licenses": [ + { + "type": "MIT", + "url": "http://www.opensource.org/licenses/MIT" + } + ], + "main": "./index", "maintainers": [ { "name": "jaredhanson", "email": "jaredhanson@gmail.com" } ], - "directories": {}, - "_shasum": "0294fb922bb9375153541c4f7096231f287c8af8", - "_resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz" + "name": "utils-merge", + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "version": "1.0.0" } diff --git a/node_modules/express/node_modules/type-is/.npmignore b/node_modules/vary/.npmignore similarity index 100% rename from node_modules/express/node_modules/type-is/.npmignore rename to node_modules/vary/.npmignore diff --git a/node_modules/express/node_modules/vary/History.md b/node_modules/vary/History.md similarity index 100% rename from node_modules/express/node_modules/vary/History.md rename to node_modules/vary/History.md diff --git a/node_modules/express/node_modules/vary/LICENSE b/node_modules/vary/LICENSE similarity index 100% rename from node_modules/express/node_modules/vary/LICENSE rename to node_modules/vary/LICENSE diff --git a/node_modules/express/node_modules/vary/README.md b/node_modules/vary/README.md similarity index 100% rename from node_modules/express/node_modules/vary/README.md rename to node_modules/vary/README.md diff --git a/node_modules/express/node_modules/vary/index.js b/node_modules/vary/index.js similarity index 100% rename from node_modules/express/node_modules/vary/index.js rename to node_modules/vary/index.js diff --git a/node_modules/express/node_modules/vary/package.json b/node_modules/vary/package.json similarity index 74% rename from node_modules/express/node_modules/vary/package.json rename to node_modules/vary/package.json index cdcdf2f..7027539 100644 --- a/node_modules/express/node_modules/vary/package.json +++ b/node_modules/vary/package.json @@ -1,49 +1,62 @@ { - "name": "vary", - "description": "Update the Vary header of a response", - "version": "0.1.0", + "_from": "vary@0.1.0", + "_id": "vary@0.1.0", + "_inBundle": false, + "_integrity": "sha1-3wlFiZ6TwMxb0YzIMh2dIedPYXY=", + "_location": "/vary", + "_npmUser": { + "name": "dougwilson", + "email": "doug@somethingdoug.com" + }, + "_npmVersion": "1.4.3", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "vary@0.1.0", + "name": "vary", + "escapedName": "vary", + "rawSpec": "0.1.0", + "saveSpec": null, + "fetchSpec": "0.1.0" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz", + "_shasum": "df0945899e93c0cc5bd18cc8321d9d21e74f6176", + "_spec": "vary@0.1.0", + "_where": "E:\\github\\node-dc-mongo\\node_modules\\express", "author": { "name": "Douglas Christopher Wilson", "email": "doug@somethingdoug.com" }, - "license": "MIT", - "keywords": [ - "http", - "res", - "vary" - ], - "repository": { - "type": "git", - "url": "git://github.com/expressjs/vary" + "bugs": { + "url": "https://github.com/expressjs/vary/issues" }, + "bundleDependencies": false, + "deprecated": false, + "description": "Update the Vary header of a response", "devDependencies": { "istanbul": "0.2.10", "mocha": "~1.20.0", "should": "~4.0.0" }, - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "mocha --reporter dot test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" - }, - "bugs": { - "url": "https://github.com/expressjs/vary/issues" - }, - "homepage": "https://github.com/expressjs/vary", - "_id": "vary@0.1.0", + "directories": {}, "dist": { "shasum": "df0945899e93c0cc5bd18cc8321d9d21e74f6176", "tarball": "http://registry.npmjs.org/vary/-/vary-0.1.0.tgz" }, - "_from": "vary@0.1.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "dougwilson", - "email": "doug@somethingdoug.com" + "engines": { + "node": ">= 0.8.0" }, + "homepage": "https://github.com/expressjs/vary", + "keywords": [ + "http", + "res", + "vary" + ], + "license": "MIT", "maintainers": [ { "name": "dougwilson", @@ -66,7 +79,15 @@ "email": "tj@vision-media.ca" } ], - "directories": {}, - "_shasum": "df0945899e93c0cc5bd18cc8321d9d21e74f6176", - "_resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz" + "name": "vary", + "repository": { + "type": "git", + "url": "git://github.com/expressjs/vary.git" + }, + "scripts": { + "test": "mocha --reporter dot test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec test/" + }, + "version": "0.1.0" } From 0626c009759685af387605c321436e58a5fee30b Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:44:21 +0800 Subject: [PATCH 03/10] change package --- app/models/SubjectViews.js | 2 +- package-lock.json | 586 ++++++++++++++++++++----------------- package.json | 29 +- 3 files changed, 347 insertions(+), 270 deletions(-) diff --git a/app/models/SubjectViews.js b/app/models/SubjectViews.js index c7e8930..e4eda34 100644 --- a/app/models/SubjectViews.js +++ b/app/models/SubjectViews.js @@ -1,4 +1,4 @@ // define our nerd model // module.exports allows us to pass this to other files when it is called -module.exports = connectionsubject.model('', {}, 'projects'); +// module.exports = connectionsubject.model('', {}, 'projects'); diff --git a/package-lock.json b/package-lock.json index eda34b4..5905b51 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,15 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "accepts": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz", + "integrity": "sha1-W1AftPBwQwmWTM2wSBclQSCNqxo=", + "requires": { + "mime-types": "~1.0.0", + "negotiator": "0.4.7" + } + }, "bluebird": { "version": "2.10.2", "resolved": "http://registry.npmjs.org/bluebird/-/bluebird-2.10.2.tgz", @@ -76,12 +85,29 @@ } }, "bson": { - "version": "0.2.22", - "resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", - "integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", - "requires": { - "nan": "~1.8" - } + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.0.tgz", + "integrity": "sha512-9Aeai9TacfNtWXOYarkFJRW2CWo+dRon+fuLZYJmvLV3+MiUp0bEI6IAZfXEIg7/Pl/7IWlLaDnhzTsD81etQA==" + }, + "buffer-crc32": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz", + "integrity": "sha1-u1RRnpXRB8vSQA520MqxRnM22SE=" + }, + "circular-json": { + "version": "0.5.9", + "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.5.9.tgz", + "integrity": "sha512-4ivwqHpIFJZBuhN3g/pEcdbnGUywkBblloGbkglyloVjjR3uT6tieI89MVOfbP2tHX5sgb01FuLgAOzebNlJNQ==" + }, + "cookie": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz", + "integrity": "sha1-cv7D0k5Io0Mgc9kMEmQgBQYQBLE=" + }, + "cookie-signature": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.4.tgz", + "integrity": "sha1-Dt0iKG46ERuaKnDbNj6SXoZ/aso=" }, "debug": { "version": "2.2.0", @@ -98,9 +124,24 @@ } } }, + "depd": { + "version": "0.3.0", + "resolved": "http://registry.npmjs.org/depd/-/depd-0.3.0.tgz", + "integrity": "sha1-Ecm8KOQlMl+9iziUC+/2n6UyaIM=" + }, + "ee-first": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", + "integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=" + }, + "escape-html": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz", + "integrity": "sha1-GBoobq05ejmpKFfPsdQwUuNWv/A=" + }, "express": { "version": "4.5.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.5.1.tgz", + "resolved": "http://registry.npmjs.org/express/-/express-4.5.1.tgz", "integrity": "sha1-S8Pm7J2yjldf5ZHDb7t4H/72/nw=", "requires": { "accepts": "~1.0.7", @@ -127,267 +168,58 @@ "vary": "0.1.0" }, "dependencies": { - "accepts": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.0.7.tgz", - "integrity": "sha1-W1AftPBwQwmWTM2wSBclQSCNqxo=", - "requires": { - "mime-types": "~1.0.0", - "negotiator": "0.4.7" - }, - "dependencies": { - "mime-types": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", - "integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=" - }, - "negotiator": { - "version": "0.4.7", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz", - "integrity": "sha1-pBYPcXfsgGc4Yx0NMFIyXaQqvcg=" - } - } - }, - "buffer-crc32": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.3.tgz", - "integrity": "sha1-u1RRnpXRB8vSQA520MqxRnM22SE=" - }, - "cookie": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.2.tgz", - "integrity": "sha1-cv7D0k5Io0Mgc9kMEmQgBQYQBLE=" - }, - "cookie-signature": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.4.tgz", - "integrity": "sha1-Dt0iKG46ERuaKnDbNj6SXoZ/aso=" - }, "debug": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "resolved": "http://registry.npmjs.org/debug/-/debug-1.0.2.tgz", "integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", "requires": { "ms": "0.6.2" - }, - "dependencies": { - "ms": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" - } - } - }, - "depd": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-0.3.0.tgz", - "integrity": "sha1-Ecm8KOQlMl+9iziUC+/2n6UyaIM=" - }, - "escape-html": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.1.tgz", - "integrity": "sha1-GBoobq05ejmpKFfPsdQwUuNWv/A=" - }, - "finalhandler": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz", - "integrity": "sha1-BgPYde6H1WeiZmkoFcyK1E/M7to=", - "requires": { - "debug": "1.0.2", - "escape-html": "1.0.1" - } - }, - "fresh": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz", - "integrity": "sha1-lzHc9WeMf660T7kDxPct9VGH+nc=" - }, - "media-typer": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", - "integrity": "sha1-2KBlITrf6qLnYyGitt2jb/YzWYQ=" - }, - "merge-descriptors": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", - "integrity": "sha1-w2pSp4FDdRPFcnXzndnTF1FKyMc=" - }, - "methods": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz", - "integrity": "sha1-dbyRlD3/19oDfPPusO1zoAN80Us=" - }, - "parseurl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", - "integrity": "sha1-Llfc5u/dN8NRhwEDCUTCK/OIt7Q=" - }, - "path-to-regexp": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz", - "integrity": "sha1-mysVH5zDAYye6lDKlXKeBXgXErQ=" - }, - "proxy-addr": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz", - "integrity": "sha1-x8Vm1etOP61n7rnHfFVYzMObiKg=", - "requires": { - "ipaddr.js": "0.1.2" - }, - "dependencies": { - "ipaddr.js": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz", - "integrity": "sha1-ah/T2FT1ACllw017vNm0qNSwRn4=" - } } }, - "qs": { - "version": "0.6.6", - "resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz", - "integrity": "sha1-bgFQmP9RlouKPIGQAdXyyJvEsQc=" - }, - "range-parser": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz", - "integrity": "sha1-pLJkz+C+XONqvjdlrJwqJIdG28A=" - }, - "send": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.5.0.tgz", - "integrity": "sha1-/A9+L5Limuv9ihst60o5TnpTGmg=", - "requires": { - "debug": "1.0.2", - "escape-html": "1.0.1", - "finished": "1.2.2", - "fresh": "0.2.2", - "mime": "1.2.11", - "ms": "0.6.2", - "range-parser": "~1.0.0" - }, - "dependencies": { - "finished": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", - "integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", - "requires": { - "ee-first": "1.0.3" - }, - "dependencies": { - "ee-first": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", - "integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=" - } - } - }, - "mime": { - "version": "1.2.11", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", - "integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=" - }, - "ms": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" - } - } - }, - "serve-static": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz", - "integrity": "sha1-2QSmy/VfURx4E49vRe5uadnRBco=", - "requires": { - "escape-html": "1.0.1", - "parseurl": "~1.1.3", - "send": "0.6.0" - }, - "dependencies": { - "parseurl": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz", - "integrity": "sha1-HwBXOKxxtBe8LQhFy9+iqLY+pjk=" - }, - "send": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.6.0.tgz", - "integrity": "sha1-pZ2pJl23w1FB4Qec8fNo7g1Zs6s=", - "requires": { - "debug": "1.0.3", - "depd": "0.3.0", - "escape-html": "1.0.1", - "finished": "1.2.2", - "fresh": "0.2.2", - "mime": "1.2.11", - "ms": "0.6.2", - "range-parser": "~1.0.0" - }, - "dependencies": { - "debug": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-1.0.3.tgz", - "integrity": "sha1-/IxrLWACgEtAgcAgjg9kYLofo+Q=", - "requires": { - "ms": "0.6.2" - } - }, - "finished": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", - "integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", - "requires": { - "ee-first": "1.0.3" - }, - "dependencies": { - "ee-first": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.0.3.tgz", - "integrity": "sha1-bJjECJq+y1p7hcGsRJqmA9Oz2r4=" - } - } - }, - "mime": { - "version": "1.2.11", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", - "integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=" - }, - "ms": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" - } - } - } - } - }, - "type-is": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz", - "integrity": "sha1-TypdxYd1yhYwJQr8cYb4s2MJ0bs=", + "ms": { + "version": "0.6.2", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + } + } + }, + "finalhandler": { + "version": "0.0.2", + "resolved": "http://registry.npmjs.org/finalhandler/-/finalhandler-0.0.2.tgz", + "integrity": "sha1-BgPYde6H1WeiZmkoFcyK1E/M7to=", + "requires": { + "debug": "1.0.2", + "escape-html": "1.0.1" + }, + "dependencies": { + "debug": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", "requires": { - "media-typer": "0.2.0", - "mime-types": "~1.0.1" - }, - "dependencies": { - "mime-types": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", - "integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=" - } + "ms": "0.6.2" } }, - "utils-merge": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", - "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=" - }, - "vary": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz", - "integrity": "sha1-3wlFiZ6TwMxb0YzIMh2dIedPYXY=" + "ms": { + "version": "0.6.2", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" } } }, + "finished": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/finished/-/finished-1.2.2.tgz", + "integrity": "sha1-QWCOr639ZWg7RqEiC8Sx7D2u3Ng=", + "requires": { + "ee-first": "1.0.3" + } + }, + "fresh": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.2.tgz", + "integrity": "sha1-lzHc9WeMf660T7kDxPct9VGH+nc=" + }, "hooks": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz", @@ -399,6 +231,11 @@ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "optional": true }, + "ipaddr.js": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-0.1.2.tgz", + "integrity": "sha1-ah/T2FT1ACllw017vNm0qNSwRn4=" + }, "kerberos": { "version": "0.0.11", "resolved": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.11.tgz", @@ -408,6 +245,22 @@ "nan": "~1.8" } }, + "media-typer": { + "version": "0.2.0", + "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.2.0.tgz", + "integrity": "sha1-2KBlITrf6qLnYyGitt2jb/YzWYQ=" + }, + "memory-pager": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.1.0.tgz", + "integrity": "sha512-Mf9OHV/Y7h6YWDxTzX/b4ZZ4oh9NSXblQL8dtPCOomOtZciEHxePR78+uHFLLlsk01A6jVHhHsQZZ/WcIPpnzg==", + "optional": true + }, + "merge-descriptors": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.2.tgz", + "integrity": "sha1-w2pSp4FDdRPFcnXzndnTF1FKyMc=" + }, "method-override": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/method-override/-/method-override-2.0.2.tgz", @@ -435,14 +288,39 @@ } } }, + "methods": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.0.1.tgz", + "integrity": "sha1-dbyRlD3/19oDfPPusO1zoAN80Us=" + }, + "mime": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.2.11.tgz", + "integrity": "sha1-WCA+7Ybjpe8XrtK32evUfwpg3RA=" + }, + "mime-types": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz", + "integrity": "sha1-mVrhOSq4r/y/yyZB3QVOlDwNXc4=" + }, "mongodb": { - "version": "1.4.38", - "resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", - "integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.1.9.tgz", + "integrity": "sha512-f+Og32wK/ovzVlC1S6Ft7yjVTvNsAOs6pBpDrPd2/3wPO9ijNsQrTNntuECjOSxGZpPVl0aRqgHzF1e9e+KvnQ==", + "requires": { + "mongodb-core": "3.1.8", + "safe-buffer": "^5.1.2" + } + }, + "mongodb-core": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.8.tgz", + "integrity": "sha512-reWCqIRNehyuLaqaz5JMOmh3Xd8JIjNX34o8mnewXLK2Fyt/Ky6BZbU+X0OPzy8qbX+JZrOtnuay7ASCieTYZw==", "requires": { - "bson": "~0.2", - "kerberos": "0.0.11", - "readable-stream": "^3.0.6" + "bson": "^1.1.0", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" } }, "mongoose": { @@ -459,6 +337,26 @@ "muri": "1.1.0", "regexp-clone": "0.0.1", "sliced": "0.0.5" + }, + "dependencies": { + "bson": { + "version": "0.2.22", + "resolved": "http://registry.npmjs.org/bson/-/bson-0.2.22.tgz", + "integrity": "sha1-/NoQPybQwHTVpS1Qkn24D9ArSzk=", + "requires": { + "nan": "~1.8" + } + }, + "mongodb": { + "version": "1.4.38", + "resolved": "http://registry.npmjs.org/mongodb/-/mongodb-1.4.38.tgz", + "integrity": "sha1-jP/WGBAK86RkiplUmL/Py07Yq9I=", + "requires": { + "bson": "~0.2", + "kerberos": "0.0.11", + "readable-stream": "^3.0.6" + } + } } }, "mpath": { @@ -497,6 +395,39 @@ "resolved": "http://registry.npmjs.org/nan/-/nan-1.8.4.tgz", "integrity": "sha1-PHa1OC6rM+RLdY0oE8qdkuk0LzQ=" }, + "negotiator": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.4.7.tgz", + "integrity": "sha1-pBYPcXfsgGc4Yx0NMFIyXaQqvcg=" + }, + "parseurl": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.0.1.tgz", + "integrity": "sha1-Llfc5u/dN8NRhwEDCUTCK/OIt7Q=" + }, + "path-to-regexp": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.2.tgz", + "integrity": "sha1-mysVH5zDAYye6lDKlXKeBXgXErQ=" + }, + "proxy-addr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-1.0.1.tgz", + "integrity": "sha1-x8Vm1etOP61n7rnHfFVYzMObiKg=", + "requires": { + "ipaddr.js": "0.1.2" + } + }, + "qs": { + "version": "0.6.6", + "resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz", + "integrity": "sha1-bgFQmP9RlouKPIGQAdXyyJvEsQc=" + }, + "range-parser": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.0.0.tgz", + "integrity": "sha1-pLJkz+C+XONqvjdlrJwqJIdG28A=" + }, "readable-stream": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.0.6.tgz", @@ -513,17 +444,127 @@ "resolved": "https://registry.npmjs.org/regexp-clone/-/regexp-clone-0.0.1.tgz", "integrity": "sha1-p8LgmJH9vzj7sQ03b7cwA+aKxYk=" }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + } + }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "optional": true + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "saslprep": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.2.tgz", + "integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==", + "optional": true, + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "semver": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==" + }, + "send": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.5.0.tgz", + "integrity": "sha1-/A9+L5Limuv9ihst60o5TnpTGmg=", + "requires": { + "debug": "1.0.2", + "escape-html": "1.0.1", + "finished": "1.2.2", + "fresh": "0.2.2", + "mime": "1.2.11", + "ms": "0.6.2", + "range-parser": "~1.0.0" + }, + "dependencies": { + "debug": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/debug/-/debug-1.0.2.tgz", + "integrity": "sha1-OElZHBDM5khHbDx8Li40FttZY8Q=", + "requires": { + "ms": "0.6.2" + } + }, + "ms": { + "version": "0.6.2", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + } + } + }, + "serve-static": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.3.2.tgz", + "integrity": "sha1-2QSmy/VfURx4E49vRe5uadnRBco=", + "requires": { + "escape-html": "1.0.1", + "parseurl": "~1.1.3", + "send": "0.6.0" + }, + "dependencies": { + "debug": { + "version": "1.0.3", + "resolved": "http://registry.npmjs.org/debug/-/debug-1.0.3.tgz", + "integrity": "sha1-/IxrLWACgEtAgcAgjg9kYLofo+Q=", + "requires": { + "ms": "0.6.2" + } + }, + "ms": { + "version": "0.6.2", + "resolved": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz", + "integrity": "sha1-2JwhJMb9wTU9Zai3e/GqxLGTcIw=" + }, + "parseurl": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.1.3.tgz", + "integrity": "sha1-HwBXOKxxtBe8LQhFy9+iqLY+pjk=" + }, + "send": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.6.0.tgz", + "integrity": "sha1-pZ2pJl23w1FB4Qec8fNo7g1Zs6s=", + "requires": { + "debug": "1.0.3", + "depd": "0.3.0", + "escape-html": "1.0.1", + "finished": "1.2.2", + "fresh": "0.2.2", + "mime": "1.2.11", + "ms": "0.6.2", + "range-parser": "~1.0.0" + } + } + } }, "sliced": { "version": "0.0.5", "resolved": "https://registry.npmjs.org/sliced/-/sliced-0.0.5.tgz", "integrity": "sha1-XtwETKTrb3gW1Qui/GPiXY/kcH8=" }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "optional": true, + "requires": { + "memory-pager": "^1.0.2" + } + }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -533,11 +574,30 @@ "safe-buffer": "~5.1.0" } }, + "type-is": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.3.2.tgz", + "integrity": "sha1-TypdxYd1yhYwJQr8cYb4s2MJ0bs=", + "requires": { + "media-typer": "0.2.0", + "mime-types": "~1.0.1" + } + }, "util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "optional": true + }, + "utils-merge": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.0.tgz", + "integrity": "sha1-ApT7kiu5N1FTVBxPcJYjHyh8ivg=" + }, + "vary": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/vary/-/vary-0.1.0.tgz", + "integrity": "sha1-3wlFiZ6TwMxb0YzIMh2dIedPYXY=" } } } diff --git a/package.json b/package.json index 872f8b5..404f238 100644 --- a/package.json +++ b/package.json @@ -3,9 +3,26 @@ "main": "server.js", "version": "1.0.1", "dependencies": { - "express" : "~4.5.1", - "mongoose" : "~3.8.0", - "body-parser" : "~1.4.2", - "method-override" : "~2.0.2" - } -} \ No newline at end of file + "body-parser": "~1.4.2", + "circular-json": "^0.5.9", + "express": "^4.5.1", + "method-override": "~2.0.2", + "mongodb": "^3.1.9", + "mongoose": "~3.8.0" + }, + "scripts": { + "start": "node server.js" + }, + "description": "

Source code for the project demonstrating data visualization using d3.js, dc.js, node.js and mongodb


", + "devDependencies": {}, + "repository": { + "type": "git", + "url": "git+https://github.com/rayyuan90/node-dc-mongo.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/rayyuan90/node-dc-mongo/issues" + }, + "homepage": "https://github.com/rayyuan90/node-dc-mongo#readme" +} From 15180e5eb11ea2f5915b76c4edd66b8f5e85adc7 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:45:12 +0800 Subject: [PATCH 04/10] change data query tool using mongo client --- server.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/server.js b/server.js index 24b6e35..ad59cee 100644 --- a/server.js +++ b/server.js @@ -4,20 +4,29 @@ var app = express(); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); +const MongoClient = require('mongodb').MongoClient // configuration =========================================== - + // config files -var port = process.env.PORT || 8080; // set our port +var port = process.env.PORT || 3000; // set our port var db = require('./config/db'); // connect to our mongoDB database (commented out after you enter in your own credentials) -connectionsubject = mongoose.createConnection(db.urlSubjectViews); +// connectionsubject = mongoose.createConnection(db.urlSubjectViews); + +MongoClient.connect('mongodb://localhost:27017/', { useNewUrlParser: true },(err, client) => { + // ... start the server + if (err) return; + db = client.db('donorschoose') + collection = db.collection('projects'); + + }) // get all data/stuff of the body (POST) parameters -app.use(bodyParser.json()); // parse application/json +app.use(bodyParser.json()); // parse application/json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded @@ -28,6 +37,6 @@ app.use(express.static(__dirname + '/public')); // set the static files location require('./app/routes')(app); // pass our application into our routes // start app =============================================== -app.listen(port); +app.listen(port); console.log('Magic happens on port ' + port); // shoutout to the user -exports = module.exports = app; // expose app \ No newline at end of file +exports = module.exports = app; // expose app From d4d27ce70186ba6e2212d5ac9fb15d9f22331459 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:45:51 +0800 Subject: [PATCH 05/10] data query function changed with findOne --- app/routes.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/app/routes.js b/app/routes.js index 5f60ecf..fc43e90 100644 --- a/app/routes.js +++ b/app/routes.js @@ -1,23 +1,25 @@ var Subjects = require('./models/SubjectViews'); +var CircularJSON = require('circular-json'); module.exports = function(app) { // server routes =========================================================== // handle things like api calls - // authentication routes + // authentication routes // sample api route app.get('/api/data', function(req, res) { // use mongoose to get all nerds in the database - Subjects.find({}, {'_id': 0, 'school_state': 1, 'resource_type': 1, 'poverty_level': 1, 'date_posted': 1, 'total_donations': 1, 'funding_status': 1, 'grade_level': 1}, function(err, subjectDetails) { - // if there is an error retrieving, send the error. + collection.findOne({}, function(err, subjectDetails) { + // if there is an error retrieving, send the error. // nothing after res.send(err) will execute - if (err) + if (err) res.send(err); - res.json(subjectDetails); // return all nerds in JSON format + let json = CircularJSON.stringify(subjectDetails); + res.send(json); // return all nerds in JSON format }); }); - + @@ -25,4 +27,4 @@ module.exports = function(app) { app.get('*', function(req, res) { res.sendfile('./public/login.html'); }); -} \ No newline at end of file +} From cd531202ed500f6ef87c0d238b40079ab4791750 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:46:58 +0800 Subject: [PATCH 06/10] change mongo connection method --- server.js | 1 + 1 file changed, 1 insertion(+) diff --git a/server.js b/server.js index ad59cee..ae594ec 100644 --- a/server.js +++ b/server.js @@ -6,6 +6,7 @@ var bodyParser = require('body-parser'); var methodOverride = require('method-override'); const MongoClient = require('mongodb').MongoClient + // configuration =========================================== // config files From dc023d1118d17a6c7ab4f8f36cd81b70a14aff58 Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Thu, 8 Nov 2018 15:47:38 +0800 Subject: [PATCH 07/10] change bson path --- node_modules/bson/ext/index.js | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 node_modules/bson/ext/index.js diff --git a/node_modules/bson/ext/index.js b/node_modules/bson/ext/index.js new file mode 100644 index 0000000..5550fcf --- /dev/null +++ b/node_modules/bson/ext/index.js @@ -0,0 +1,41 @@ +var bson = null; + +try { + // 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('bson'); + } +} catch(err) { + // Attempt to load the release bson version + try { + bson = require('bson'); + } catch (err) { + console.dir(err) + console.error("js-bson: Failed to load c++ bson extension, using pure JS version"); + bson = require('../lib/bson/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; From 58b3fc88c5fcabfb33d795ab2e0a8c1b636692ae Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Fri, 9 Nov 2018 15:47:43 +0800 Subject: [PATCH 08/10] add find condition and limit to 100 --- app/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.js b/app/routes.js index fc43e90..52f9341 100644 --- a/app/routes.js +++ b/app/routes.js @@ -9,7 +9,7 @@ module.exports = function(app) { // sample api route app.get('/api/data', function(req, res) { // use mongoose to get all nerds in the database - collection.findOne({}, function(err, subjectDetails) { + collection.find({},{'_id': 0, 'school_state': 1, 'resource_type': 1, 'poverty_level': 1, 'date_posted': 1, 'total_donations': 1, 'funding_status': 1, 'grade_level': 1}).limit(100).toArray(function(err, subjectDetails) { // if there is an error retrieving, send the error. // nothing after res.send(err) will execute if (err) From 821fd1450109a41cf5db1dc1c3b38ef1ffc00f4c Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Fri, 9 Nov 2018 17:26:46 +0800 Subject: [PATCH 09/10] beauty code --- public/js/Dashboard.js | 352 ++++++++++++++++++++++------------------- 1 file changed, 192 insertions(+), 160 deletions(-) diff --git a/public/js/Dashboard.js b/public/js/Dashboard.js index ed93a94..03359b3 100644 --- a/public/js/Dashboard.js +++ b/public/js/Dashboard.js @@ -1,166 +1,198 @@ queue() - .defer(d3.json, "/api/data") - .await(makeGraphs); + .defer(d3.json, "/api/data") + .await(makeGraphs); function makeGraphs(error, apiData) { - -//Start Transformations - var dataSet = apiData; - var dateFormat = d3.time.format("%m/%d/%Y"); - dataSet.forEach(function(d) { - d.date_posted = dateFormat.parse(d.date_posted); - d.date_posted.setDate(1); - d.total_donations = +d.total_donations; - }); - - //Create a Crossfilter instance - var ndx = crossfilter(dataSet); - - //Define Dimensions - var datePosted = ndx.dimension(function(d) { return d.date_posted; }); - var gradeLevel = ndx.dimension(function(d) { return d.grade_level; }); - var resourceType = ndx.dimension(function(d) { return d.resource_type; }); - var fundingStatus = ndx.dimension(function(d) { return d.funding_status; }); - var povertyLevel = ndx.dimension(function(d) { return d.poverty_level; }); - var state = ndx.dimension(function(d) { return d.school_state; }); - var totalDonations = ndx.dimension(function(d) { return d.total_donations; }); - - - //Calculate metrics - var projectsByDate = datePosted.group(); - var projectsByGrade = gradeLevel.group(); - var projectsByResourceType = resourceType.group(); - var projectsByFundingStatus = fundingStatus.group(); - var projectsByPovertyLevel = povertyLevel.group(); - var stateGroup = state.group(); - - var all = ndx.groupAll(); - - //Calculate Groups - var totalDonationsState = state.group().reduceSum(function(d) { - return d.total_donations; - }); - - var totalDonationsGrade = gradeLevel.group().reduceSum(function(d) { - return d.grade_level; - }); - - var totalDonationsFundingStatus = fundingStatus.group().reduceSum(function(d) { - return d.funding_status; - }); - - - - var netTotalDonations = ndx.groupAll().reduceSum(function(d) {return d.total_donations;}); - - //Define threshold values for data - var minDate = datePosted.bottom(1)[0].date_posted; - var maxDate = datePosted.top(1)[0].date_posted; - -console.log(minDate); -console.log(maxDate); - - //Charts - var dateChart = dc.lineChart("#date-chart"); - var gradeLevelChart = dc.rowChart("#grade-chart"); - var resourceTypeChart = dc.rowChart("#resource-chart"); - var fundingStatusChart = dc.pieChart("#funding-chart"); - var povertyLevelChart = dc.rowChart("#poverty-chart"); - var totalProjects = dc.numberDisplay("#total-projects"); - var netDonations = dc.numberDisplay("#net-donations"); - var stateDonations = dc.barChart("#state-donations"); + + //Start Transformations + var dataSet = apiData; + var dateFormat = d3.time.format("%m/%d/%Y"); + dataSet.forEach(function(d) { + d.date_posted = dateFormat.parse(d.date_posted); + d.date_posted.setDate(1); + d.total_donations = +d.total_donations; + }); + + //Create a Crossfilter instance + var ndx = crossfilter(dataSet); + + //Define Dimensions + var datePosted = ndx.dimension(function(d) { + return d.date_posted; + }); + var gradeLevel = ndx.dimension(function(d) { + return d.grade_level; + }); + var resourceType = ndx.dimension(function(d) { + return d.resource_type; + }); + var fundingStatus = ndx.dimension(function(d) { + return d.funding_status; + }); + var povertyLevel = ndx.dimension(function(d) { + return d.poverty_level; + }); + var state = ndx.dimension(function(d) { + return d.school_state; + }); + var totalDonations = ndx.dimension(function(d) { + return d.total_donations; + }); + + + //Calculate metrics + var projectsByDate = datePosted.group(); + var projectsByGrade = gradeLevel.group(); + var projectsByResourceType = resourceType.group(); + var projectsByFundingStatus = fundingStatus.group(); + var projectsByPovertyLevel = povertyLevel.group(); + var stateGroup = state.group(); + + var all = ndx.groupAll(); + + //Calculate Groups + var totalDonationsState = state.group().reduceSum(function(d) { + return d.total_donations; + }); + + var totalDonationsGrade = gradeLevel.group().reduceSum(function(d) { + return d.grade_level; + }); + + var totalDonationsFundingStatus = fundingStatus.group().reduceSum(function(d) { + return d.funding_status; + }); + + + + var netTotalDonations = ndx.groupAll().reduceSum(function(d) { + return d.total_donations; + }); + + //Define threshold values for data + var minDate = datePosted.bottom(1)[0].date_posted; + var maxDate = datePosted.top(1)[0].date_posted; + + console.log(minDate); + console.log(maxDate); + + //Charts + var dateChart = dc.lineChart("#date-chart"); + var gradeLevelChart = dc.rowChart("#grade-chart"); + var resourceTypeChart = dc.rowChart("#resource-chart"); + var fundingStatusChart = dc.pieChart("#funding-chart"); + var povertyLevelChart = dc.rowChart("#poverty-chart"); + var totalProjects = dc.numberDisplay("#total-projects"); + var netDonations = dc.numberDisplay("#net-donations"); + var stateDonations = dc.barChart("#state-donations"); selectField = dc.selectMenu('#menuselect') - .dimension(state) - .group(stateGroup); - - dc.dataCount("#row-selection") - .dimension(ndx) - .group(all); - - - totalProjects - .formatNumber(d3.format("d")) - .valueAccessor(function(d){return d; }) - .group(all); - - netDonations - .formatNumber(d3.format("d")) - .valueAccessor(function(d){return d; }) - .group(netTotalDonations) - .formatNumber(d3.format(".3s")); - - dateChart - //.width(600) - .height(220) - .margins({top: 10, right: 50, bottom: 30, left: 50}) - .dimension(datePosted) - .group(projectsByDate) - .renderArea(true) - .transitionDuration(500) - .x(d3.time.scale().domain([minDate, maxDate])) - .elasticY(true) - .renderHorizontalGridLines(true) - .renderVerticalGridLines(true) - .xAxisLabel("Year") - .yAxis().ticks(6); - - resourceTypeChart - //.width(300) - .height(220) - .dimension(resourceType) - .group(projectsByResourceType) - .elasticX(true) - .xAxis().ticks(5); - - povertyLevelChart - //.width(300) - .height(220) - .dimension(povertyLevel) - .group(projectsByPovertyLevel) - .xAxis().ticks(4); - - gradeLevelChart - //.width(300) - .height(220) - .dimension(gradeLevel) - .group(projectsByGrade) - .xAxis().ticks(4); - - - fundingStatusChart - .height(220) - //.width(350) - .radius(90) - .innerRadius(40) - .transitionDuration(1000) - .dimension(fundingStatus) - .group(projectsByFundingStatus); - - - stateDonations - //.width(800) - .height(220) - .transitionDuration(1000) - .dimension(state) - .group(totalDonationsState) - .margins({top: 10, right: 50, bottom: 30, left: 50}) - .centerBar(false) - .gap(5) - .elasticY(true) - .x(d3.scale.ordinal().domain(state)) - .xUnits(dc.units.ordinal) - .renderHorizontalGridLines(true) - .renderVerticalGridLines(true) - .ordering(function(d){return d.value;}) - .yAxis().tickFormat(d3.format("s")); - - - - - - - dc.renderAll(); - -}; \ No newline at end of file + .dimension(state) + .group(stateGroup); + + dc.dataCount("#row-selection") + .dimension(ndx) + .group(all); + + + totalProjects + .formatNumber(d3.format("d")) + .valueAccessor(function(d) { + return d; + }) + .group(all); + + netDonations + .formatNumber(d3.format("d")) + .valueAccessor(function(d) { + return d; + }) + .group(netTotalDonations) + .formatNumber(d3.format(".3s")); + + dateChart + //.width(600) + .height(220) + .margins({ + top: 10, + right: 50, + bottom: 30, + left: 50 + }) + .dimension(datePosted) + .group(projectsByDate) + .renderArea(true) + .transitionDuration(500) + .x(d3.time.scale().domain([minDate, maxDate])) + .elasticY(true) + .renderHorizontalGridLines(true) + .renderVerticalGridLines(true) + .xAxisLabel("Year") + .yAxis().ticks(6); + + resourceTypeChart + //.width(300) + .height(220) + .dimension(resourceType) + .group(projectsByResourceType) + .elasticX(true) + .xAxis().ticks(5); + + povertyLevelChart + //.width(300) + .height(220) + .dimension(povertyLevel) + .group(projectsByPovertyLevel) + .xAxis().ticks(4); + + gradeLevelChart + //.width(300) + .height(220) + .dimension(gradeLevel) + .group(projectsByGrade) + .xAxis().ticks(4); + + + fundingStatusChart + .height(220) + //.width(350) + .radius(90) + .innerRadius(40) + .transitionDuration(1000) + .dimension(fundingStatus) + .group(projectsByFundingStatus); + + + stateDonations + //.width(800) + .height(220) + .transitionDuration(1000) + .dimension(state) + .group(totalDonationsState) + .margins({ + top: 10, + right: 50, + bottom: 30, + left: 50 + }) + .centerBar(false) + .gap(5) + .elasticY(true) + .x(d3.scale.ordinal().domain(state)) + .xUnits(dc.units.ordinal) + .renderHorizontalGridLines(true) + .renderVerticalGridLines(true) + .ordering(function(d) { + return d.value; + }) + .yAxis().tickFormat(d3.format("s")); + + + + + + + dc.renderAll(); + +}; From f913bf88d3cec5eaedec995dfd8d9bc18507803a Mon Sep 17 00:00:00 2001 From: rayyuan90 Date: Mon, 12 Nov 2018 10:03:23 +0800 Subject: [PATCH 10/10] add data number select --- app/routes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes.js b/app/routes.js index 52f9341..f4c541b 100644 --- a/app/routes.js +++ b/app/routes.js @@ -9,7 +9,7 @@ module.exports = function(app) { // sample api route app.get('/api/data', function(req, res) { // use mongoose to get all nerds in the database - collection.find({},{'_id': 0, 'school_state': 1, 'resource_type': 1, 'poverty_level': 1, 'date_posted': 1, 'total_donations': 1, 'funding_status': 1, 'grade_level': 1}).limit(100).toArray(function(err, subjectDetails) { + collection.find({},{'_id': 0, 'school_state': 1, 'resource_type': 1, 'poverty_level': 1, 'date_posted': 1, 'total_donations': 1, 'funding_status': 1, 'grade_level': 1}).limit(10000).toArray(function(err, subjectDetails) { // if there is an error retrieving, send the error. // nothing after res.send(err) will execute if (err)