From 7e692a8d32e87557c2d032fd7158a4f2317d970a Mon Sep 17 00:00:00 2001 From: Ibrahim Shaker Date: Thu, 9 Sep 2021 17:05:30 +0200 Subject: [PATCH] initial commit, build rabbitmq publisher --- node_modules/amqplib/.npmignore | 8 + node_modules/amqplib/CHANGELOG.md | 349 + node_modules/amqplib/LICENSE | 6 + node_modules/amqplib/LICENSE-MIT | 21 + node_modules/amqplib/Makefile | 48 + node_modules/amqplib/README.md | 155 + node_modules/amqplib/bin/generate-defs.js | 723 +++ node_modules/amqplib/callback_api.js | 22 + node_modules/amqplib/channel_api.js | 16 + node_modules/amqplib/examples/headers.js | 42 + .../amqplib/examples/receive_generator.js | 39 + .../amqplib/examples/send_generators.js | 42 + node_modules/amqplib/examples/ssl.js | 64 + .../amqplib/examples/tutorials/README.md | 93 + .../tutorials/callback_api/emit_log.js | 28 + .../tutorials/callback_api/emit_log_direct.js | 30 + .../tutorials/callback_api/emit_log_topic.js | 27 + .../tutorials/callback_api/new_task.js | 27 + .../tutorials/callback_api/receive.js | 30 + .../tutorials/callback_api/receive_logs.js | 36 + .../callback_api/receive_logs_direct.js | 56 + .../callback_api/receive_logs_topic.js | 55 + .../tutorials/callback_api/rpc_client.js | 49 + .../tutorials/callback_api/rpc_server.js | 45 + .../examples/tutorials/callback_api/send.js | 29 + .../examples/tutorials/callback_api/worker.js | 35 + .../amqplib/examples/tutorials/emit_log.js | 19 + .../examples/tutorials/emit_log_direct.js | 20 + .../examples/tutorials/emit_log_topic.js | 19 + .../amqplib/examples/tutorials/new_task.js | 18 + .../amqplib/examples/tutorials/package.json | 16 + .../amqplib/examples/tutorials/receive.js | 21 + .../examples/tutorials/receive_logs.js | 28 + .../examples/tutorials/receive_logs_direct.js | 45 + .../examples/tutorials/receive_logs_topic.js | 44 + .../amqplib/examples/tutorials/rpc_client.js | 53 + .../amqplib/examples/tutorials/rpc_server.js | 39 + .../amqplib/examples/tutorials/send.js | 23 + .../amqplib/examples/tutorials/worker.js | 28 + .../amqplib/examples/waitForConfirms.js | 22 + node_modules/amqplib/lib/api_args.js | 314 + node_modules/amqplib/lib/bitset.js | 103 + node_modules/amqplib/lib/callback_model.js | 328 + node_modules/amqplib/lib/channel.js | 498 ++ node_modules/amqplib/lib/channel_model.js | 318 + node_modules/amqplib/lib/codec.js | 321 + node_modules/amqplib/lib/connect.js | 185 + node_modules/amqplib/lib/connection.js | 647 ++ node_modules/amqplib/lib/credentials.js | 43 + node_modules/amqplib/lib/defs.js | 4966 ++++++++++++++ node_modules/amqplib/lib/error.js | 24 + node_modules/amqplib/lib/format.js | 40 + node_modules/amqplib/lib/frame.js | 114 + node_modules/amqplib/lib/heartbeat.js | 89 + node_modules/amqplib/lib/mux.js | 131 + node_modules/amqplib/package-lock.json | 1623 +++++ node_modules/amqplib/package.json | 71 + node_modules/amqplib/test/bitset.js | 68 + node_modules/amqplib/test/callback_api.js | 313 + node_modules/amqplib/test/channel.js | 624 ++ node_modules/amqplib/test/channel_api.js | 597 ++ node_modules/amqplib/test/codec.js | 238 + node_modules/amqplib/test/connect.js | 152 + node_modules/amqplib/test/connection.js | 391 ++ node_modules/amqplib/test/data.js | 255 + node_modules/amqplib/test/frame.js | 199 + node_modules/amqplib/test/mux.js | 204 + node_modules/amqplib/test/util.js | 220 + node_modules/bitsyntax/.travis.yml | 12 + node_modules/bitsyntax/LICENSE | 6 + node_modules/bitsyntax/LICENSE-MIT | 21 + node_modules/bitsyntax/Makefile | 15 + node_modules/bitsyntax/README.md | 306 + node_modules/bitsyntax/index.js | 10 + node_modules/bitsyntax/lib/compile.js | 303 + node_modules/bitsyntax/lib/constructor.js | 142 + node_modules/bitsyntax/lib/grammar.pegjs | 67 + node_modules/bitsyntax/lib/interp.js | 232 + node_modules/bitsyntax/lib/parse.js | 32 + node_modules/bitsyntax/lib/parser.js | 1173 ++++ node_modules/bitsyntax/lib/pattern.js | 116 + .../node_modules/safe-buffer/LICENSE | 21 + .../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/bitsyntax/package.json | 60 + node_modules/bitsyntax/test/consing.js | 47 + node_modules/bitsyntax/test/matching.js | 188 + node_modules/bluebird/LICENSE | 21 + node_modules/bluebird/README.md | 57 + node_modules/bluebird/changelog.md | 1 + .../bluebird/js/browser/bluebird.core.js | 3914 +++++++++++ .../bluebird/js/browser/bluebird.core.min.js | 31 + node_modules/bluebird/js/browser/bluebird.js | 5778 +++++++++++++++++ .../bluebird/js/browser/bluebird.min.js | 31 + node_modules/bluebird/js/release/any.js | 21 + node_modules/bluebird/js/release/assert.js | 55 + node_modules/bluebird/js/release/async.js | 120 + node_modules/bluebird/js/release/bind.js | 67 + node_modules/bluebird/js/release/bluebird.js | 11 + node_modules/bluebird/js/release/call_get.js | 123 + node_modules/bluebird/js/release/cancel.js | 129 + .../bluebird/js/release/catch_filter.js | 42 + node_modules/bluebird/js/release/context.js | 69 + .../bluebird/js/release/debuggability.js | 1009 +++ .../bluebird/js/release/direct_resolve.js | 46 + node_modules/bluebird/js/release/each.js | 30 + node_modules/bluebird/js/release/errors.js | 116 + node_modules/bluebird/js/release/es5.js | 80 + node_modules/bluebird/js/release/filter.js | 12 + node_modules/bluebird/js/release/finally.js | 146 + .../bluebird/js/release/generators.js | 223 + node_modules/bluebird/js/release/join.js | 165 + node_modules/bluebird/js/release/map.js | 175 + node_modules/bluebird/js/release/method.js | 55 + node_modules/bluebird/js/release/nodeback.js | 51 + node_modules/bluebird/js/release/nodeify.js | 58 + node_modules/bluebird/js/release/promise.js | 819 +++ .../bluebird/js/release/promise_array.js | 186 + node_modules/bluebird/js/release/promisify.js | 314 + node_modules/bluebird/js/release/props.js | 118 + node_modules/bluebird/js/release/queue.js | 73 + node_modules/bluebird/js/release/race.js | 49 + node_modules/bluebird/js/release/reduce.js | 183 + node_modules/bluebird/js/release/schedule.js | 62 + node_modules/bluebird/js/release/settle.js | 47 + node_modules/bluebird/js/release/some.js | 148 + .../js/release/synchronous_inspection.js | 103 + node_modules/bluebird/js/release/thenables.js | 86 + node_modules/bluebird/js/release/timers.js | 93 + node_modules/bluebird/js/release/using.js | 226 + node_modules/bluebird/js/release/util.js | 421 ++ node_modules/bluebird/package.json | 102 + node_modules/buffer-more-ints/.travis.yml | 6 + node_modules/buffer-more-ints/LICENSE | 19 + node_modules/buffer-more-ints/README.md | 69 + .../buffer-more-ints-tests.js | 183 + .../buffer-more-ints/buffer-more-ints.js | 432 ++ node_modules/buffer-more-ints/package.json | 51 + node_modules/buffer-more-ints/polyfill.js | 71 + node_modules/core-util-is/LICENSE | 19 + node_modules/core-util-is/README.md | 3 + node_modules/core-util-is/lib/util.js | 107 + node_modules/core-util-is/package.json | 68 + node_modules/debug/.coveralls.yml | 1 + node_modules/debug/.eslintrc | 11 + node_modules/debug/.npmignore | 9 + node_modules/debug/.travis.yml | 14 + node_modules/debug/CHANGELOG.md | 362 ++ node_modules/debug/LICENSE | 19 + node_modules/debug/Makefile | 50 + node_modules/debug/README.md | 312 + node_modules/debug/component.json | 19 + node_modules/debug/karma.conf.js | 70 + node_modules/debug/node.js | 1 + node_modules/debug/package.json | 88 + node_modules/debug/src/browser.js | 185 + node_modules/debug/src/debug.js | 202 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/inspector-log.js | 15 + node_modules/debug/src/node.js | 248 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 9 + node_modules/inherits/inherits_browser.js | 27 + node_modules/inherits/package.json | 61 + 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 | 57 + node_modules/ms/index.js | 152 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 69 + node_modules/ms/readme.md | 51 + node_modules/querystringify/LICENSE | 22 + node_modules/querystringify/README.md | 61 + node_modules/querystringify/index.js | 118 + node_modules/querystringify/package.json | 65 + node_modules/readable-stream/.npmignore | 5 + node_modules/readable-stream/LICENSE | 18 + node_modules/readable-stream/README.md | 15 + node_modules/readable-stream/duplex.js | 1 + node_modules/readable-stream/float.patch | 923 +++ .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 951 +++ .../readable-stream/lib/_stream_transform.js | 209 + .../readable-stream/lib/_stream_writable.js | 477 ++ node_modules/readable-stream/package.json | 65 + node_modules/readable-stream/passthrough.js | 1 + node_modules/readable-stream/readable.js | 10 + node_modules/readable-stream/transform.js | 1 + node_modules/readable-stream/writable.js | 1 + node_modules/requires-port/.npmignore | 2 + node_modules/requires-port/.travis.yml | 19 + node_modules/requires-port/LICENSE | 22 + node_modules/requires-port/README.md | 47 + node_modules/requires-port/index.js | 38 + node_modules/requires-port/package.json | 74 + node_modules/requires-port/test.js | 98 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 ++ node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 65 + node_modules/safe-buffer/package.json | 76 + 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 | 53 + node_modules/url-parse/LICENSE | 22 + node_modules/url-parse/README.md | 147 + node_modules/url-parse/dist/url-parse.js | 692 ++ node_modules/url-parse/dist/url-parse.min.js | 1 + .../url-parse/dist/url-parse.min.js.map | 1 + node_modules/url-parse/index.js | 526 ++ node_modules/url-parse/package.json | 80 + package-lock.json | 116 + package.json | 15 + publisher.js | 27 + 222 files changed, 44533 insertions(+) create mode 100644 node_modules/amqplib/.npmignore create mode 100644 node_modules/amqplib/CHANGELOG.md create mode 100644 node_modules/amqplib/LICENSE create mode 100644 node_modules/amqplib/LICENSE-MIT create mode 100644 node_modules/amqplib/Makefile create mode 100644 node_modules/amqplib/README.md create mode 100644 node_modules/amqplib/bin/generate-defs.js create mode 100644 node_modules/amqplib/callback_api.js create mode 100644 node_modules/amqplib/channel_api.js create mode 100644 node_modules/amqplib/examples/headers.js create mode 100644 node_modules/amqplib/examples/receive_generator.js create mode 100644 node_modules/amqplib/examples/send_generators.js create mode 100644 node_modules/amqplib/examples/ssl.js create mode 100644 node_modules/amqplib/examples/tutorials/README.md create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/emit_log.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/new_task.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/receive.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/send.js create mode 100644 node_modules/amqplib/examples/tutorials/callback_api/worker.js create mode 100644 node_modules/amqplib/examples/tutorials/emit_log.js create mode 100644 node_modules/amqplib/examples/tutorials/emit_log_direct.js create mode 100644 node_modules/amqplib/examples/tutorials/emit_log_topic.js create mode 100644 node_modules/amqplib/examples/tutorials/new_task.js create mode 100644 node_modules/amqplib/examples/tutorials/package.json create mode 100644 node_modules/amqplib/examples/tutorials/receive.js create mode 100644 node_modules/amqplib/examples/tutorials/receive_logs.js create mode 100644 node_modules/amqplib/examples/tutorials/receive_logs_direct.js create mode 100644 node_modules/amqplib/examples/tutorials/receive_logs_topic.js create mode 100644 node_modules/amqplib/examples/tutorials/rpc_client.js create mode 100644 node_modules/amqplib/examples/tutorials/rpc_server.js create mode 100644 node_modules/amqplib/examples/tutorials/send.js create mode 100644 node_modules/amqplib/examples/tutorials/worker.js create mode 100644 node_modules/amqplib/examples/waitForConfirms.js create mode 100644 node_modules/amqplib/lib/api_args.js create mode 100644 node_modules/amqplib/lib/bitset.js create mode 100644 node_modules/amqplib/lib/callback_model.js create mode 100644 node_modules/amqplib/lib/channel.js create mode 100644 node_modules/amqplib/lib/channel_model.js create mode 100644 node_modules/amqplib/lib/codec.js create mode 100644 node_modules/amqplib/lib/connect.js create mode 100644 node_modules/amqplib/lib/connection.js create mode 100644 node_modules/amqplib/lib/credentials.js create mode 100644 node_modules/amqplib/lib/defs.js create mode 100644 node_modules/amqplib/lib/error.js create mode 100644 node_modules/amqplib/lib/format.js create mode 100644 node_modules/amqplib/lib/frame.js create mode 100644 node_modules/amqplib/lib/heartbeat.js create mode 100644 node_modules/amqplib/lib/mux.js create mode 100644 node_modules/amqplib/package-lock.json create mode 100644 node_modules/amqplib/package.json create mode 100644 node_modules/amqplib/test/bitset.js create mode 100644 node_modules/amqplib/test/callback_api.js create mode 100644 node_modules/amqplib/test/channel.js create mode 100644 node_modules/amqplib/test/channel_api.js create mode 100644 node_modules/amqplib/test/codec.js create mode 100644 node_modules/amqplib/test/connect.js create mode 100644 node_modules/amqplib/test/connection.js create mode 100644 node_modules/amqplib/test/data.js create mode 100644 node_modules/amqplib/test/frame.js create mode 100644 node_modules/amqplib/test/mux.js create mode 100644 node_modules/amqplib/test/util.js create mode 100644 node_modules/bitsyntax/.travis.yml create mode 100644 node_modules/bitsyntax/LICENSE create mode 100644 node_modules/bitsyntax/LICENSE-MIT create mode 100644 node_modules/bitsyntax/Makefile create mode 100644 node_modules/bitsyntax/README.md create mode 100644 node_modules/bitsyntax/index.js create mode 100644 node_modules/bitsyntax/lib/compile.js create mode 100644 node_modules/bitsyntax/lib/constructor.js create mode 100644 node_modules/bitsyntax/lib/grammar.pegjs create mode 100644 node_modules/bitsyntax/lib/interp.js create mode 100644 node_modules/bitsyntax/lib/parse.js create mode 100644 node_modules/bitsyntax/lib/parser.js create mode 100644 node_modules/bitsyntax/lib/pattern.js create mode 100644 node_modules/bitsyntax/node_modules/safe-buffer/LICENSE create mode 100644 node_modules/bitsyntax/node_modules/safe-buffer/README.md create mode 100644 node_modules/bitsyntax/node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/bitsyntax/node_modules/safe-buffer/index.js create mode 100644 node_modules/bitsyntax/node_modules/safe-buffer/package.json create mode 100644 node_modules/bitsyntax/package.json create mode 100644 node_modules/bitsyntax/test/consing.js create mode 100644 node_modules/bitsyntax/test/matching.js create mode 100644 node_modules/bluebird/LICENSE create mode 100644 node_modules/bluebird/README.md create mode 100644 node_modules/bluebird/changelog.md create mode 100644 node_modules/bluebird/js/browser/bluebird.core.js create mode 100644 node_modules/bluebird/js/browser/bluebird.core.min.js 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/release/any.js create mode 100644 node_modules/bluebird/js/release/assert.js create mode 100644 node_modules/bluebird/js/release/async.js create mode 100644 node_modules/bluebird/js/release/bind.js create mode 100644 node_modules/bluebird/js/release/bluebird.js create mode 100644 node_modules/bluebird/js/release/call_get.js create mode 100644 node_modules/bluebird/js/release/cancel.js create mode 100644 node_modules/bluebird/js/release/catch_filter.js create mode 100644 node_modules/bluebird/js/release/context.js create mode 100644 node_modules/bluebird/js/release/debuggability.js create mode 100644 node_modules/bluebird/js/release/direct_resolve.js create mode 100644 node_modules/bluebird/js/release/each.js create mode 100644 node_modules/bluebird/js/release/errors.js create mode 100644 node_modules/bluebird/js/release/es5.js create mode 100644 node_modules/bluebird/js/release/filter.js create mode 100644 node_modules/bluebird/js/release/finally.js create mode 100644 node_modules/bluebird/js/release/generators.js create mode 100644 node_modules/bluebird/js/release/join.js create mode 100644 node_modules/bluebird/js/release/map.js create mode 100644 node_modules/bluebird/js/release/method.js create mode 100644 node_modules/bluebird/js/release/nodeback.js create mode 100644 node_modules/bluebird/js/release/nodeify.js create mode 100644 node_modules/bluebird/js/release/promise.js create mode 100644 node_modules/bluebird/js/release/promise_array.js create mode 100644 node_modules/bluebird/js/release/promisify.js create mode 100644 node_modules/bluebird/js/release/props.js create mode 100644 node_modules/bluebird/js/release/queue.js create mode 100644 node_modules/bluebird/js/release/race.js create mode 100644 node_modules/bluebird/js/release/reduce.js create mode 100644 node_modules/bluebird/js/release/schedule.js create mode 100644 node_modules/bluebird/js/release/settle.js create mode 100644 node_modules/bluebird/js/release/some.js create mode 100644 node_modules/bluebird/js/release/synchronous_inspection.js create mode 100644 node_modules/bluebird/js/release/thenables.js create mode 100644 node_modules/bluebird/js/release/timers.js create mode 100644 node_modules/bluebird/js/release/using.js create mode 100644 node_modules/bluebird/js/release/util.js create mode 100644 node_modules/bluebird/package.json create mode 100644 node_modules/buffer-more-ints/.travis.yml create mode 100644 node_modules/buffer-more-ints/LICENSE create mode 100644 node_modules/buffer-more-ints/README.md create mode 100644 node_modules/buffer-more-ints/buffer-more-ints-tests.js create mode 100644 node_modules/buffer-more-ints/buffer-more-ints.js create mode 100644 node_modules/buffer-more-ints/package.json create mode 100644 node_modules/buffer-more-ints/polyfill.js create mode 100644 node_modules/core-util-is/LICENSE create mode 100644 node_modules/core-util-is/README.md create mode 100644 node_modules/core-util-is/lib/util.js create mode 100644 node_modules/core-util-is/package.json create mode 100644 node_modules/debug/.coveralls.yml create mode 100644 node_modules/debug/.eslintrc create mode 100644 node_modules/debug/.npmignore create mode 100644 node_modules/debug/.travis.yml create mode 100644 node_modules/debug/CHANGELOG.md create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/Makefile create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/component.json create mode 100644 node_modules/debug/karma.conf.js create mode 100644 node_modules/debug/node.js create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/debug.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/inspector-log.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/isarray/README.md create mode 100644 node_modules/isarray/build/build.js create mode 100644 node_modules/isarray/component.json create mode 100644 node_modules/isarray/index.js create mode 100644 node_modules/isarray/package.json create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/querystringify/LICENSE create mode 100644 node_modules/querystringify/README.md create mode 100644 node_modules/querystringify/index.js create mode 100644 node_modules/querystringify/package.json create mode 100644 node_modules/readable-stream/.npmignore create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/duplex.js create mode 100644 node_modules/readable-stream/float.patch create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/passthrough.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/readable-stream/transform.js create mode 100644 node_modules/readable-stream/writable.js create mode 100644 node_modules/requires-port/.npmignore create mode 100644 node_modules/requires-port/.travis.yml create mode 100644 node_modules/requires-port/LICENSE create mode 100644 node_modules/requires-port/README.md create mode 100644 node_modules/requires-port/index.js create mode 100644 node_modules/requires-port/package.json create mode 100644 node_modules/requires-port/test.js create mode 100644 node_modules/safe-buffer/LICENSE 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 create mode 100644 node_modules/string_decoder/.npmignore create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/index.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/url-parse/LICENSE create mode 100644 node_modules/url-parse/README.md create mode 100644 node_modules/url-parse/dist/url-parse.js create mode 100644 node_modules/url-parse/dist/url-parse.min.js create mode 100644 node_modules/url-parse/dist/url-parse.min.js.map create mode 100644 node_modules/url-parse/index.js create mode 100644 node_modules/url-parse/package.json create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 publisher.js diff --git a/node_modules/amqplib/.npmignore b/node_modules/amqplib/.npmignore new file mode 100644 index 0000000..4ec9397 --- /dev/null +++ b/node_modules/amqplib/.npmignore @@ -0,0 +1,8 @@ +*~ +scratch +# do not ignore lib/defs.js, we need that +# node_modules is ignored anyway +.travis.yml +bin/amqp-rabbitmq-0.9.1.json +etc/ +coverage/ diff --git a/node_modules/amqplib/CHANGELOG.md b/node_modules/amqplib/CHANGELOG.md new file mode 100644 index 0000000..5426d6b --- /dev/null +++ b/node_modules/amqplib/CHANGELOG.md @@ -0,0 +1,349 @@ +# Change log for amqplib + +## Changes in v0.8.0 + + git log v0.7.1..v0.8.0 + + * :warning: Support for NodeJS prior to v10 is dropped :warning: ([PR + 615](https://github.com/squaremo/amqp.node/pull/615), thank you + @xamgore and everyone who helped there) + * Use hostname as TLS servername, to help with using servers behind + load balancers ([PR + 567](https://github.com/squaremo/amqp.node/pull/567), thanks to + @carlhoerberg and commenters) + +## Changes in v0.7.1 + + git log v0.7.0..v0.7.1 + + * Update url-parse (and others) ([PR + 607](https://github.com/squaremo/amqp.node/pull/545), thanks + @ThomasGawlitza) + +## Changes in v0.7.0 + + git log v0.6.0..v0.7.0 + + * Extend support to Node.js v15 + * Fix use of stream.write in tests + +## Changes in v0.6.0 + + git log v0.5.6..v0.6.0 + + * Extend support to Node.js v14 + +## Changes in v0.5.6 + + git log v0.5.5..v0.5.6 + + * Increase size of encoding space for message headers, to fit e.g., + JWT ([PR 545](https://github.com/squaremo/amqp.node/pull/545)); + thanks @twatson83 + * Switch to a non-deprecated UUID module ([PR + 528](https://github.com/squaremo/amqp.node/pull/528)); thanks to + @StrayBird-ATSH + * Fix a bug in multiplexing that caused an assertion to fail ([PR + 503](https://github.com/squaremo/amqp.node/pull/503)); thanks + @johanneswuerbach + +## Changes in v0.5.5 + + git log v0.5.3..v0.5.5 + +**NB** this includes a minor but possibly breaking change: after [PR +498](https://github.com/squaremo/amqp.node/pull/498), all confirmation +promises still unresolved will be rejected when their associated +channel is closed. + + * Generate defs in `npm prepare` rather than `npm prepublish` so that + e.g., amqplib can be installed via git ([part of PR + 498](https://github.com/squaremo/amqp.node/pull/498)) + * Reject all pending confirmations when the channel is closed ([PR + 498](https://github.com/squaremo/amqp.node/pull/498)); thanks + @johanneswuerbach + * Update supported NodeJS versions in package.json ([PR + 525](https://github.com/squaremo/amqp.node/pull/525)); thanks + @tingwai + +## (Deprecated v0.5.4) + +This release was mistakenly published without the generated file +`./defs.js`. It has been deprecated in favour of v0.5.5. + +## Changes in v0.5.3 + + git log v0.5.2..v0.5.3 + + * Bump bitsyntax to remove some `Buffer` misuse deprecation notices + ([PR 480])(https://github.com/squaremo/amqp.node/pull/480) + * Test on node 11.1 + ([PR 473])(https://github.com/squaremo/amqp.node/pull/464); thanks + @kibertoad + * Updated various dependencies + * Support queue mode during assertQueue + ([PR 464])(https://github.com/squaremo/amqp.node/pull/464); thanks + @JoeTheFkingFrypan + * Expose serverProperties in the connection object + ([PR 452])(https://github.com/squaremo/amqp.node/pull/452); thanks + @jfromaniello + * Test on Node 10 + ([PR 454])(https://github.com/squaremo/amqp.node/pull/454); thanks + @kibertoad + * Support amqplain credentials + ([PR 451])(https://github.com/squaremo/amqp.node/pull/451); thanks + @jfromaniello + * Decorate channel errors with methodId and classId + ([PR 447])(https://github.com/squaremo/amqp.node/pull/447); thanks + @MitMaro + * Resolve issues caused by Node 10 `readable` changes + ([PR 442])(https://github.com/squaremo/amqp.node/pull/442) + * Bump uglify to 2.6.x and node to 9.1 due to nodejs/node#16781. + ([PR 439])(https://github.com/squaremo/amqp.node/pull/439) + * Updated README with more modern Buffer syntax + ([PR 438](https://github.com/squaremo/amqp.node/pull/438); thanks + @ravshansbox + * Support overflow option to assert queue + ([PR 436])(https://github.com/squaremo/amqp.node/pull/436); thanks + to @honestserpent + * Replace instances of keyword `await` + ([PR 396])(https://github.com/squaremo/amqp.node/pull/396), + as discussed in + [issue 235](https://github.com/squaremo/amqp.node/issues/235) + * Use 3rd party url for better decoding of username/password + ([PR 395])(https://github.com/squaremo/amqp.node/pull/395), + as discussed in + [issue 385](https://github.com/squaremo/amqp.node/issues/385)) + +## Changes in v0.5.2 + + git log v0.5.1..v0.5.2 + + * Increase encoding buffer to accommodate large header values + ([PR 367](https://github.com/squaremo/amqp.node/pull/367)) + * Bring code up to date with new Buffer interface + ([PR 350](https://github.com/squaremo/amqp.node/pull/350)) + * Fix dangling connection problem + ([PR 340](https://github.com/squaremo/amqp.node/pull/340)) + * Clear up URL credentials parsing + ([PR 330](https://github.com/squaremo/amqp.node/pull/330)) + * Allow connection params to be suppied in object + ([PR 304](https://github.com/squaremo/amqp.node/pull/304)) + * Support explicit numeric types in field tables (e.g., headers) + ([PR 389](https://github.com/squaremo/amqp.node/pull/389), from a + suggestion in + [issue 358](https://github.com/squaremo/amqp.node/issues/358)) + +Thank you to all contributors, of PRs, issues and comments. + +## Changes in v0.5.1 + + git log v0.5.0..v0.5.1 + + * Fix mistake in closeBecause + ([PR 298](https://github.com/squaremo/amqp.node/pull/298); thanks + to @lholznagel and others who reported the issue, and to @nfantone + for the rapid fix) + +## Changes in v0.5.0 + + git log v0.4.2..v0.5.0 + + * Port to use bluebird rather than when.js + ([PR 295](https://github.com/squaremo/amqp.node/pull/295); thanks + to @nfantone, and special mention to @myndzi for #158) + * Fixed a problem with using `channel.get` in the callback model + ([PR 283](https://github.com/squaremo/amqp.node/pull/283); good + catch, @shanksauce) + * Added an example that uses generators (thanks @rudijs) + * Fixed a link in the comments relating to heartbeats (thanks + @tapickell) + +## Changes in v0.4.2 + + git log v0.4.1..v0.4.2 + + * Better documentation and examples + * Replace uses of ES6 keyword 'await' + +## Changes in v0.4.1 + + git log v0.4.0..v0.4.1 + + * Tested in Node.JS 0.8 through 4.2 and 5.5 + * Emit an error with the 'close' event if server-initiated + +## Changes in v0.4.0 + + git log v0.3.2..v0.4.0 + + * Tested on Node.JS 0.8 through 4.0 (and intervening io.js releases) + * Change meaning of 'b' fields in tables to match RabbitMQ (and AMQP + specification) + * Can now pass an object in place of connection URL + ([PR 159](https://github.com/squaremo/amqp.node/pull/159); thanks + to @ben-page) + * Operator-initiated connection close no longer results in 'error' + event + ([issue 110](https://github.com/squaremo/amqp.node/issues/110)) + * Channel and Connection errors have now a `.code` field with the + AMQP reply-code, which may help distinguish error cases + ([PR 150](https://github.com/squaremo/amqp.node/pull/150); thanks + to @hippich) + * Connection.close will resolve to an error if the connection is + already closed + ([issue 181](https://github.com/squaremo/amqp.node/issues/181)) + * Connection establishment will resolve with an error if the + TCP-level connection or the handshake times out + ([PR 169](https://github.com/squaremo/amqp.node/pull/169); thanks + to @zweifisch and @RoCat, who both submitted fixes) + * Add the `maxPriority` option as an alias for the `'x-max-priority'` + queue argument + ([PR 180](https://github.com/squaremo/amqp.node/pull/180); thanks + to @ebardes) + +## Changes in v0.3.2 (since v0.3.1) + + git log v0.3.1..v0.3.2 + + * Make the engine specification more flexible to admit io.js releases + +## Changes in v0.3.1 (since v0.3.0) + + git log v0.3.0..v0.3.1 + +### Fixes + + * Fail in the right way when a channel cannot be allocated [issue + 129](https://github.com/squaremo/amqp.node/issues/129) + * Make `waitForConfirms` work properly in callback API [PR + 116](https://github.com/squaremo/amqp.node/pull/116) + +### Enhancements + + * Two new options while connecting: + [timeout](https://github.com/squaremo/amqp.node/pull/118) and [keep + alive](https://github.com/squaremo/amqp.node/pull/125) (thanks to + @rexxars and @jcrugzz respectively) + +## Changes in v0.3.0 (since v0.2.1) + + git log v0.2.1..v0.3.0 + +### Enhancements + + * Allow additional client properties to be set for a connection + [Issue 98](https://github.com/squaremo/amqp.node/issues/98) and + [PR 80](https://github.com/squaremo/amqp.node/pull/80) + * New method in channel API to wait for all unconfirmed messages + [Issue 89](https://github.com/squaremo/amqp.node/issues/89) + * Now supports RabbitMQ's `EXTERNAL` authentication plugin + [Issue 105](https://github.com/squaremo/amqp.node/issues/105) + +## Changes in v0.2.1 (since v0.2.0) + +### Fixes + + * Do tuning negotation properly [PR + 84](https://github.com/squaremo/amqp.node/pull/84) + +## Changes in v0.2.0 (since v0.1.3) + + git log v0.1.3..v0.2.0 + +### Fixes + + * Correctly deal with missing fields (issue 48) + +### Enhancements + + * Added a callback-oriented API, parallel to the existing, + promise-oriented API. + * The response to assertExchange now contains the exchange name, + analagous to assertQueue (issue 49) + * The channel method `prefetch` now has a global flag, to be + [compatible with newer RabbitMQ][rabbitmq-prefetch-global]. + +## Changes in v0.1.3 (since v0.1.2) + + git log v0.1.2..v0.1.3 + +### Enhancements + + * Add support in the API for using Basic.Reject rather than + Basic.Nack, the latter of which is a RabbitMQ extension and not in + older versions of RabbitMQ. + +## Changes in v0.1.2 (since v0.1.1) + + git log v0.1.1..v0.1.2 + +### Fixes + + * Restore support for publishing zero-length messages + +### Enhancements + + * Recognise [authentication failures][rabbitmq-auth-failure] + * An option to set TCP_NODELAY on connection sockets + +## Changes in v0.1.1 (since v0.1.0) + + git log v0.1.0..v0.1.1 + +### Fixes + + * Safer frame construction, no longer relies on allocating a large, + fixed-size buffer and hoping it's big enough + * The ports of RabbitMQ tutorials now avoid a race between publishing + and closing the connection + +### Enhancements + + * Support for RabbitMQ's consumer priority extension + * Support for RabbitMQ's connnection.blocked extension + * Better write speed from batching frames for small messages + * Other minor efficiency gains in method encoding and decoding + * Channel and connection state errors (e.g., trying to write when + closed) include a stack trace from when they moved to that state + * The `arguments` table, passed as an option to some methods, can + include fields in its prototype chain + * Provide the more accurately named `persistent` as a near equivalent + of `deliveryMode` + +## Changes in v0.1.0 (since v0.0.2) + + git log v0.0.2..v0.1.0 + +### Breaking changes + + * Consumer callbacks are invoked with `null` if the consumer is + cancelled (see + [RabbitMQ's consumer cancel notification][rabbitmq-consumer-cancel]) + * In confirm channels, instead of `#publish` and `#sendToQueue` + returning promises, they return a boolean as for normal channels, + and take a Node.JS-style `function (err, ok)` callback for the + server ack or nack + +### Fixes + + * Overlapping channel and connection close frames are dealt with + gracefully + * Exceptions thrown in consumer callbacks are raised as `'error'` + events + * Zero-size messages are handled + * Avoid monkey-patching `Buffer`, and eschew + `require('util')._extend` + +### Enhancements + + * Channels now behave like `Writable` streams with regard to `#publish` + and `#sendToQueue`, returning a boolean from those methods and + emitting `'drain'` + * Connections now multiplex frames from channels fairly + * Low-level channel machinery is now fully callback-based + + +[rabbitmq-consumer-cancel]: http://www.rabbitmq.com/consumer-cancel.html +[rabbitmq-auth-failure]: http://www.rabbitmq.com/auth-notification.html +[rabbitmq-prefetch-global]: http://www.rabbitmq.com/consumer-prefetch.html diff --git a/node_modules/amqplib/LICENSE b/node_modules/amqplib/LICENSE new file mode 100644 index 0000000..62c710d --- /dev/null +++ b/node_modules/amqplib/LICENSE @@ -0,0 +1,6 @@ +amqplib copyright (c) 2013, 2014 + Michael Bridgen + +This package, "amqplib", is licensed under the MIT License. A copy may +be found in the file LICENSE-MIT in this directory, or downloaded from +http://opensource.org/licenses/MIT. diff --git a/node_modules/amqplib/LICENSE-MIT b/node_modules/amqplib/LICENSE-MIT new file mode 100644 index 0000000..d04bc01 --- /dev/null +++ b/node_modules/amqplib/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013, 2014 Michael Bridgen + +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/amqplib/Makefile b/node_modules/amqplib/Makefile new file mode 100644 index 0000000..e139332 --- /dev/null +++ b/node_modules/amqplib/Makefile @@ -0,0 +1,48 @@ +RABBITMQ_SRC_VERSION=rabbitmq_v3_2_1 +JSON=amqp-rabbitmq-0.9.1.json +RABBITMQ_CODEGEN=https://raw.githubusercontent.com/rabbitmq/rabbitmq-codegen +AMQP_JSON=$(RABBITMQ_CODEGEN)/$(RABBITMQ_SRC_VERSION)/$(JSON) + +NODEJS_VERSIONS='10.21' '11.15' '12.18' '13.14' '14.5' '15.8' + +MOCHA=./node_modules/.bin/mocha +_MOCHA=./node_modules/.bin/_mocha +UGLIFY=./node_modules/.bin/uglifyjs +ISTANBUL=./node_modules/.bin/istanbul + +.PHONY: test test-all-nodejs all clean coverage + +all: lib/defs.js + +clean: + rm lib/defs.js bin/amqp-rabbitmq-0.9.1.json + rm -rf ./coverage + +lib/defs.js: $(UGLIFY) bin/generate-defs.js bin/amqp-rabbitmq-0.9.1.json + (cd bin; node ./generate-defs.js > ../lib/defs.js) + $(UGLIFY) ./lib/defs.js -o ./lib/defs.js \ + -c 'sequences=false' --comments \ + -b 'indent-level=2' 2>&1 | (grep -v 'WARN' || true) + +test: lib/defs.js + $(MOCHA) --check-leaks -u tdd test/ + +test-all-nodejs: lib/defs.js + for v in $(NODEJS_VERSIONS); \ + do echo "-- Node version $$v --"; \ + nave use $$v $(MOCHA) -u tdd -R progress test; \ + done + +coverage: $(ISTANBUL) lib/defs.js + $(ISTANBUL) cover $(_MOCHA) -- -u tdd -R progress test/ + $(ISTANBUL) report + @echo "HTML report at file://$$(pwd)/coverage/lcov-report/index.html" + +bin/amqp-rabbitmq-0.9.1.json: + curl -L $(AMQP_JSON) > $@ + +$(ISTANBUL): + npm install + +$(UGLIFY): + npm install diff --git a/node_modules/amqplib/README.md b/node_modules/amqplib/README.md new file mode 100644 index 0000000..a7a11b2 --- /dev/null +++ b/node_modules/amqplib/README.md @@ -0,0 +1,155 @@ +# AMQP 0-9-1 library and client for Node.JS + +[![Build Status](https://travis-ci.org/squaremo/amqp.node.png)](https://travis-ci.org/squaremo/amqp.node) + + npm install amqplib + + * [Change log][changelog] + * [GitHub pages][gh-pages] + * [API reference][gh-pages-apiref] + * [Examples from RabbitMQ tutorials][tutes] + +A library for making AMQP 0-9-1 clients for Node.JS, and an AMQP 0-9-1 client for Node.JS v10+. + +This library does not implement [AMQP +1.0](https://github.com/squaremo/amqp.node/issues/63) or [AMQP +0-10](https://github.com/squaremo/amqp.node/issues/94). + +Project status: + + - Expected to work + - Complete high-level and low-level APIs (i.e., all bits of the protocol) + - Stable APIs + - A fair few tests + - Measured test coverage + - Ports of the [RabbitMQ tutorials][rabbitmq-tutes] as [examples][tutes] + - Used in production + +Still working on: + + - Getting to 100% (or very close to 100%) test coverage + +## Callback API example + +```javascript +var q = 'tasks'; + +function bail(err) { + console.error(err); + process.exit(1); +} + +// Publisher +function publisher(conn) { + conn.createChannel(on_open); + function on_open(err, ch) { + if (err != null) bail(err); + ch.assertQueue(q); + ch.sendToQueue(q, Buffer.from('something to do')); + } +} + +// Consumer +function consumer(conn) { + var ok = conn.createChannel(on_open); + function on_open(err, ch) { + if (err != null) bail(err); + ch.assertQueue(q); + ch.consume(q, function(msg) { + if (msg !== null) { + console.log(msg.content.toString()); + ch.ack(msg); + } + }); + } +} + +require('amqplib/callback_api') + .connect('amqp://localhost', function(err, conn) { + if (err != null) bail(err); + consumer(conn); + publisher(conn); + }); +``` + +## Promise API example + +```javascript +var q = 'tasks'; + +var open = require('amqplib').connect('amqp://localhost'); + +// Publisher +open.then(function(conn) { + return conn.createChannel(); +}).then(function(ch) { + return ch.assertQueue(q).then(function(ok) { + return ch.sendToQueue(q, Buffer.from('something to do')); + }); +}).catch(console.warn); + +// Consumer +open.then(function(conn) { + return conn.createChannel(); +}).then(function(ch) { + return ch.assertQueue(q).then(function(ok) { + return ch.consume(q, function(msg) { + if (msg !== null) { + console.log(msg.content.toString()); + ch.ack(msg); + } + }); + }); +}).catch(console.warn); +``` + +## Running tests + + npm test + +To run the tests RabbitMQ is required. Either install it with your package +manager, or use [docker][] to run a RabbitMQ instance. + + docker run -d --name amqp.test -p 5672:5672 rabbitmq + +If prefer not to run RabbitMQ locally it is also possible to use a +instance of RabbitMQ hosted elsewhere. Use the `URL` environment +variable to configure a different amqp host to connect to. You may +also need to do this if docker is not on localhost; e.g., if it's +running in docker-machine. + +One public host is dev.rabbitmq.com: + + URL=amqp://dev.rabbitmq.com npm test + +**NB** You may experience test failures due to timeouts if using the +dev.rabbitmq.com instance. + +You can run it under different versions of Node.JS using [nave][]: + + nave use 0.8 npm test + +or run the tests on all supported versions of Node.JS in one go: + + make test-all-nodejs + +(which also needs `nave` installed, of course). + +Lastly, setting the environment variable `LOG_ERRORS` will cause the +tests to output error messages encountered, to the console; this is +really only useful for checking the kind and formatting of the errors. + + LOG_ERRORS=true npm test + +## Test coverage + + make coverage + open file://`pwd`/coverage/lcov-report/index.html + +[gh-pages]: http://www.squaremobius.net/amqp.node/ +[gh-pages-apiref]: http://www.squaremobius.net/amqp.node/channel_api.html +[nave]: https://github.com/isaacs/nave +[tutes]: https://github.com/squaremo/amqp.node/tree/main/examples/tutorials +[rabbitmq-tutes]: http://www.rabbitmq.com/getstarted.html +[changelog]: https://github.com/squaremo/amqp.node/blob/main/CHANGELOG.md +[docker]: https://www.docker.com/ diff --git a/node_modules/amqplib/bin/generate-defs.js b/node_modules/amqplib/bin/generate-defs.js new file mode 100644 index 0000000..af984a0 --- /dev/null +++ b/node_modules/amqplib/bin/generate-defs.js @@ -0,0 +1,723 @@ +var FS = require('fs'); +var format = require('util').format; + +var defs = require('./amqp-rabbitmq-0.9.1.json'); + +var FRAME_OVERHEAD = 8; // type + channel + size + frame-end + +var METHOD_OVERHEAD = FRAME_OVERHEAD + 4; +// F_O + classId + methodId + +var PROPERTIES_OVERHEAD = FRAME_OVERHEAD + 4 + 8 + 2; +// F_O + classId + weight + content size + flags + + +var out = process.stdout; + +function printf() { + out.write(format.apply(format, arguments), 'utf8'); +} + +function nl() { out.write('\n'); } +function println() { printf.apply(printf, arguments); nl(); } + +function isEmptyObject(val) { + return (val != null && typeof val === 'object' && + Object.keys(val).length === 0); +} + +function stringifyValue(val) { + return (isEmptyObject(val)) ? 'EMPTY_OBJECT' : + JSON.stringify(val); +} + +var constants = {}; +var constant_strs = {}; + +for (var i = 0, len = defs.constants.length; i < len; i++) { + var cdef = defs.constants[i]; + constants[constantName(cdef)] = cdef.value; + constant_strs[cdef.value] = cdef.name; +} + +function constantName(def) { + return def.name.replace(/-/g, '_'); +} + +function methodName(clazz, method) { + return initial(clazz.name) + method.name.split('-').map(initial).join(''); +} + +function propertyName(dashed) { + var parts = dashed.split('-'); + return parts[0] + parts.slice(1).map(initial).join(''); +} + +function initial(part) { + return part.charAt(0).toUpperCase() + part.substr(1); +} + +function argument(a) { + var type = a.type || domains[a.domain]; + var friendlyName = propertyName(a.name); + return {type: type, name: friendlyName, default: a['default-value']}; +} + +var domains = {}; +for (var i=0, len = defs.domains.length; i < len; i++) { + var dom = defs.domains[i]; + domains[dom[0]] = dom[1]; +} + +var methods = {}; +var propertieses = {}; + +for (var i = 0, len = defs.classes.length; i < len; i++) { + var clazz = defs.classes[i]; + for (var j = 0, num = clazz.methods.length; j < num; j++) { + var method = clazz.methods[j]; + var name = methodName(clazz, method); + var info = 'methodInfo' + name; + + methods[name] = { + id: methodId(clazz, method), + name: name, + methodId: method.id, + clazzId: clazz.id, + clazz: clazz.name, + args: method['arguments'].map(argument), + isReply: method.answer, + encoder: 'encode' + name, + decoder: 'decode' + name, + info: info + }; + } + if (clazz.properties && clazz.properties.length > 0) { + var name = propertiesName(clazz); + var props = clazz.properties; + propertieses[name] = { + id: clazz.id, + name: name, + encoder: 'encode' + name, + decoder: 'decode' + name, + info: 'propertiesInfo' + name, + args: props.map(argument), + }; + } +} + +// OK let's get emitting + +println( +'/** @preserve This file is generated by the script\n', +'* ../bin/generate-defs.js, which is not in general included in a\n', +'* distribution, but is available in the source repository e.g. at\n', +'* https://github.com/squaremo/amqp.node/\n', +'*/'); + +println("'use strict';"); nl(); +println('var Buffer = require("safe-buffer").Buffer;'); +nl() +println('var codec = require("./codec");'); +println('var ints = require("buffer-more-ints");'); +println('var encodeTable = codec.encodeTable;'); +println('var decodeFields = codec.decodeFields;'); +nl(); + +println('var SCRATCH = Buffer.alloc(65536);'); +println('var EMPTY_OBJECT = Object.freeze({});'); + +println('module.exports.constants = %s', + JSON.stringify(constants)); +nl(); +println('module.exports.constant_strs = %s', + JSON.stringify(constant_strs)); +nl(); +println('module.exports.FRAME_OVERHEAD = %d;', FRAME_OVERHEAD); +nl(); + +println('module.exports.decode = function(id, buf) {'); +println('switch (id) {'); +for (var m in methods) { + var method = methods[m]; + println('case %d: return %s(buf);', method.id, method.decoder); +} +for (var p in propertieses) { + var props = propertieses[p]; + println('case %d: return %s(buf);', props.id, props.decoder); +} +println('default: throw new Error("Unknown class/method ID");'); +println('}}'); nl(); + +println('module.exports.encodeMethod =', + 'function(id, channel, fields) {'); +println('switch (id) {'); +for (var m in methods) { + var method = methods[m]; + println('case %d: return %s(channel, fields);', + method.id, method.encoder); +} +println('default: throw new Error("Unknown class/method ID");'); +println('}}'); nl(); + +println('module.exports.encodeProperties =' + , 'function(id, channel, size, fields) {'); +println('switch (id) {'); +for (var p in propertieses) { + var props = propertieses[p]; + println('case %d: return %s(channel, size, fields);', + props.id, props.encoder); +} +println('default: throw new Error("Unknown class/properties ID");'); +println('}}'); nl(); + +println('module.exports.info = function(id) {'); +println('switch(id) {'); +for (var m in methods) { + var method = methods[m]; + println('case %d: return %s; ', method.id, method.info); +} +for (var p in propertieses) { + var properties = propertieses[p]; + println('case %d: return %s', properties.id, properties.info); +} +println('default: throw new Error("Unknown class/method ID");'); +println('}}'); nl(); + +for (var m in methods) { + var method = methods[m]; + println('module.exports.%s = %d;', m, method.id); + decoderFn(method); nl(); + encoderFn(method); nl(); + infoObj(method); nl(); +} + +for (var p in propertieses) { + var properties = propertieses[p]; + println('module.exports.%s = %d;', p, properties.id); + encodePropsFn(properties); nl(); + decodePropsFn(properties); nl(); + infoObj(properties); nl(); +} + +function methodId(clazz, method) { + return (clazz.id << 16) + method.id; +} + +function propertiesName(clazz) { + return initial(clazz.name) + 'Properties'; +} + +function valTypeTest(arg) { + switch (arg.type) { + // everything is booleany + case 'bit': return 'true' + case 'octet': + case 'short': + case 'long': + case 'longlong': + case 'timestamp': return "typeof val === 'number' && !isNaN(val)"; + case 'shortstr': return "typeof val === 'string' &&" + + " Buffer.byteLength(val) < 256"; + case 'longstr': return "Buffer.isBuffer(val)"; + case 'table': return "typeof val === 'object'"; + } +} + +function typeDesc(t) { + switch (t) { + case 'bit': return 'booleany'; + case 'octet': + case 'short': + case 'long': + case 'longlong': + case 'timestamp': return "a number (but not NaN)"; + case 'shortstr': return "a string (up to 255 chars)"; + case 'longstr': return "a Buffer"; + case 'table': return "an object"; + } +} + +function defaultValueRepr(arg) { + switch (arg.type) { + case 'longstr': + return format("Buffer.from(%s)", JSON.stringify(arg.default)); + default: + // assumes no tables as defaults + return JSON.stringify(arg.default); + } +} + +// Emit code to assign the arg value to `val`. +function assignArg(a) { + println("val = fields['%s'];", a.name); +} + +function assignOrDefault(a) { + println("val = fields['%s'];", a.name); + println("if (val === undefined) val = %s;", defaultValueRepr(a)); +} + +// Emit code for assigning an argument value to `val`, checking that +// it exists (if it does not have a default) and is the correct +// type. +function checkAssignArg(a) { + assignArg(a); + println('if (val === undefined) {'); + if (a.default !== undefined) { + println('val = %s;', defaultValueRepr(a)); + } + else { + println('throw new Error("Missing value for mandatory field \'%s\'");', a.name); + } + println('}'); // undefined test + println('else if (!(%s)) {', valTypeTest(a)); + println('throw new TypeError('); + println('"Field \'%s\' is the wrong type; must be %s");', + a.name, typeDesc(a.type)); + println('}'); // type test +} + +// Emit code for encoding `val` as a table and assign to a fresh +// variable (based on the arg name). I use a scratch buffer to compose +// the encoded table, otherwise I'd have to do a size calculation pass +// first. I can get away with this only because 1. the encoding +// procedures are not re-entrant; and, 2. I copy the result into +// another buffer before returning. `scratchOffset`, `val`, `len` are +// expected to have been declared. +function assignTable(a) { + var varname = tableVar(a); + println( + "len = encodeTable(SCRATCH, val, scratchOffset);"); + println('var %s = SCRATCH.slice(scratchOffset, scratchOffset + len);', varname); + println('scratchOffset += len;'); +} + +function tableVar(a) { + return a.name + '_encoded'; +} + +function stringLenVar(a) { + return a.name + '_len'; +} + +function assignStringLen(a) { + var v = stringLenVar(a); + // Assumes the value or default is in val + println("var %s = Buffer.byteLength(val, 'utf8');", v); +} + + +function encoderFn(method) { + var args = method['args']; + println('function %s(channel, fields) {', method.encoder); + println('var offset = 0, val = null, bits = 0, varyingSize = 0;'); + println('var len, scratchOffset = 0;'); + + // Encoding is split into two parts. Some fields have a fixed size + // (e.g., integers of a specific width), while some have a size that + // depends on the datum (e.g., strings). Each field will therefore + // either 1. contribute to the fixed size; or 2. emit code to + // calculate the size (and possibly the encoded value, in the case + // of tables). + var fixedSize = METHOD_OVERHEAD; + + var bitsInARow = 0; + + for (var i=0, len = args.length; i < len; i++) { + var arg = args[i]; + + if (arg.type != 'bit') bitsInARow = 0; + + switch (arg.type) { + // varying size + case 'shortstr': + checkAssignArg(arg); + assignStringLen(arg); + println("varyingSize += %s;", stringLenVar(arg)); + fixedSize += 1; + break; + case 'longstr': + checkAssignArg(arg); + println("varyingSize += val.length;"); + fixedSize += 4; + break; + case 'table': + // For a table we have to encode the table before we can see its + // length. + checkAssignArg(arg); + assignTable(arg); + println('varyingSize += %s.length;', tableVar(arg)); + break; + + // fixed size + case 'octet': fixedSize += 1; break; + case 'short': fixedSize += 2; break; + case 'long': fixedSize += 4; break; + case 'longlong': //fall through + case 'timestamp': + fixedSize += 8; break; + case 'bit': + bitsInARow ++; + // open a fresh pack o' bits + if (bitsInARow === 1) fixedSize += 1; + // just used a pack; reset + else if (bitsInARow === 8) bitsInARow = 0; + break; + } + } + + println('var buffer = Buffer.alloc(%d + varyingSize);', fixedSize); + + println('buffer[0] = %d;', constants.FRAME_METHOD); + println('buffer.writeUInt16BE(channel, 1);'); + // skip size for now, we'll write it in when we know + println('buffer.writeUInt32BE(%d, 7);', method.id); + println('offset = 11;'); + + bitsInARow = 0; + + for (var i = 0, len = args.length; i < len; i++) { + var a = args[i]; + + // Flush any collected bits before doing a new field + if (a.type != 'bit' && bitsInARow > 0) { + bitsInARow = 0; + println('buffer[offset] = bits; offset++; bits = 0;'); + } + + switch (a.type) { + case 'octet': + checkAssignArg(a); + println('buffer.writeUInt8(val, offset); offset++;'); + break; + case 'short': + checkAssignArg(a); + println('buffer.writeUInt16BE(val, offset); offset += 2;'); + break; + case 'long': + checkAssignArg(a); + println('buffer.writeUInt32BE(val, offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + checkAssignArg(a); + println('ints.writeUInt64BE(buffer, val, offset); offset += 8;'); + break; + case 'bit': + checkAssignArg(a); + println('if (val) bits += %d;', 1 << bitsInARow); + if (bitsInARow === 7) { // I don't think this ever happens, but whatever + println('buffer[offset] = bits; offset++; bits = 0;'); + bitsInARow = 0; + } + else bitsInARow++; + break; + case 'shortstr': + assignOrDefault(a); + println('buffer[offset] = %s; offset++;', stringLenVar(a)); + println('buffer.write(val, offset, "utf8"); offset += %s;', + stringLenVar(a)); + break; + case 'longstr': + assignOrDefault(a); + println('len = val.length;'); + println('buffer.writeUInt32BE(len, offset); offset += 4;'); + println('val.copy(buffer, offset); offset += len;'); + break; + case 'table': + println('offset += %s.copy(buffer, offset);', tableVar(a)); + break; + default: throw new Error("Unexpected argument type: " + a.type); + } + } + + // Flush any collected bits at the end + if (bitsInARow > 0) { + println('buffer[offset] = bits; offset++;'); + } + + println('buffer[offset] = %d;', constants.FRAME_END); + // size does not include the frame header or frame end byte + println('buffer.writeUInt32BE(offset - 7, 3);'); + + println('return buffer;'); + println('}'); +} + +function fieldsDecl(args) { + println('var fields = {'); + for (var i=0, num=args.length; i < num; i++) { + println('%s: undefined,', args[i].name); + } + println('};'); +} + +function decoderFn(method) { + var args = method.args; + println('function %s(buffer) {', method.decoder); + println('var offset = 0, val, len;'); + fieldsDecl(args); + + var bitsInARow = 0; + + for (var i=0, num=args.length; i < num; i++) { + var a = args[i]; + var field = "fields['" + a.name + "']"; + + // Flush any collected bits before doing a new field + if (a.type != 'bit' && bitsInARow > 0) { + bitsInARow = 0; + println('offset++;'); + } + + switch (a.type) { + case 'octet': + println('val = buffer[offset]; offset++;'); + break; + case 'short': + println('val = buffer.readUInt16BE(offset); offset += 2;'); + break; + case 'long': + println('val = buffer.readUInt32BE(offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); + break; + case 'bit': + var bit = 1 << bitsInARow; + println('val = !!(buffer[offset] & %d);', bit); + if (bitsInARow === 7) { + println('offset++;'); + bitsInARow = 0; + } + else bitsInARow++; + break; + case 'longstr': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = buffer.slice(offset, offset + len);'); + println('offset += len;'); + break; + case 'shortstr': + println('len = buffer.readUInt8(offset); offset++;'); + println('val = buffer.toString("utf8", offset, offset + len);'); + println('offset += len;'); + break; + case 'table': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = decodeFields(buffer.slice(offset, offset + len));'); + println('offset += len;'); + break; + default: + throw new TypeError("Unexpected type in argument list: " + a.type); + } + println('%s = val;', field); + } + println('return fields;'); + println('}'); +} + +function infoObj(thing) { + var info = JSON.stringify({id: thing.id, + classId: thing.clazzId, + methodId: thing.methodId, + name: thing.name, + args: thing.args}); + println('var %s = module.exports.%s = %s;', + thing.info, thing.info, info); +} + +// The flags are laid out in groups of fifteen in a short (high to +// low bits), with a continuation bit (at 0) and another group +// following if there's more than fifteen. Presence and absence +// are conflated with true and false, for bit fields (i.e., if the +// flag for the field is set, it's true, otherwise false). +// +// However, none of that is actually used in AMQP 0-9-1. The only +// instance of properties -- basic properties -- has 14 fields, none +// of them bits. + +function flagAt(index) { + return 1 << (15 - index); +} + +function encodePropsFn(props) { + println('function %s(channel, size, fields) {', props.encoder); + println('var offset = 0, flags = 0, val, len;'); + println('var scratchOffset = 0, varyingSize = 0;'); + + var fixedSize = PROPERTIES_OVERHEAD; + + var args = props.args; + + function incVarying(by) { + println("varyingSize += %d;", by); + } + + for (var i=0, num=args.length; i < num; i++) { + var p = args[i]; + + assignArg(p); + println("if (val != undefined) {"); + + println("if (%s) {", valTypeTest(p)); + switch (p.type) { + case 'shortstr': + assignStringLen(p); + incVarying(1); + println('varyingSize += %s;', stringLenVar(p)); + break; + case 'longstr': + incVarying(4); + println('varyingSize += val.length;'); + break; + case 'table': + assignTable(p); + println('varyingSize += %s.length;', tableVar(p)); + break; + case 'octet': incVarying(1); break; + case 'short': incVarying(2); break; + case 'long': incVarying(4); break; + case 'longlong': // fall through + case 'timestamp': + incVarying(8); break; + // no case for bit, as they are accounted for in the flags + } + println('} else {'); + println('throw new TypeError('); + println('"Field \'%s\' is the wrong type; must be %s");', + p.name, typeDesc(p.type)); + println('}'); + println('}'); + } + + println('var buffer = Buffer.alloc(%d + varyingSize);', fixedSize); + + println('buffer[0] = %d', constants.FRAME_HEADER); + println('buffer.writeUInt16BE(channel, 1);'); + // content class ID and 'weight' (== 0) + println('buffer.writeUInt32BE(%d, 7);', props.id << 16); + // skip frame size for now, we'll write it in when we know. + + // body size + println('ints.writeUInt64BE(buffer, size, 11);'); + + println('flags = 0;'); + // we'll write the flags later too + println('offset = 21;'); + + for (var i=0, num=args.length; i < num; i++) { + var p = args[i]; + var flag = flagAt(i); + + assignArg(p); + println("if (val != undefined) {"); + if (p.type === 'bit') { // which none of them are .. + println('if (val) flags += %d;', flag); + } + else { + println('flags += %d;', flag); + // %%% FIXME only slightly different to the method args encoding + switch (p.type) { + case 'octet': + println('buffer.writeUInt8(val, offset); offset++;'); + break; + case 'short': + println('buffer.writeUInt16BE(val, offset); offset += 2;'); + break; + case 'long': + println('buffer.writeUInt32BE(val, offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('ints.writeUInt64BE(buffer, val, offset);'); + println('offset += 8;'); + break; + case 'shortstr': + var v = stringLenVar(p); + println('buffer[offset] = %s; offset++;', v); + println("buffer.write(val, offset, 'utf8');"); + println("offset += %s;", v); + break; + case 'longstr': + println('buffer.writeUInt32BE(val.length, offset);'); + println('offset += 4;'); + println('offset += val.copy(buffer, offset);'); + break; + case 'table': + println('offset += %s.copy(buffer, offset);', tableVar(p)); + break; + default: throw new Error("Unexpected argument type: " + p.type); + } + } + println('}'); // != undefined + } + + println('buffer[offset] = %d;', constants.FRAME_END); + // size does not include the frame header or frame end byte + println('buffer.writeUInt32BE(offset - 7, 3);'); + println('buffer.writeUInt16BE(flags, 19);'); + println('return buffer.slice(0, offset + 1);'); + println('}'); +} + +function decodePropsFn(props) { + var args = props.args; + + println('function %s(buffer) {', props.decoder); + println('var flags, offset = 2, val, len;'); + + println('flags = buffer.readUInt16BE(0);'); + println('if (flags === 0) return {};'); + + fieldsDecl(args); + + for (var i=0, num=args.length; i < num; i++) { + var p = argument(args[i]); + var field = "fields['" + p.name + "']"; + + println('if (flags & %d) {', flagAt(i)); + if (p.type === 'bit') { + println('%d = true;', field); + } + else { + switch (p.type) { + case 'octet': + println('val = buffer[offset]; offset++;'); + break; + case 'short': + println('val = buffer.readUInt16BE(offset); offset += 2;'); + break; + case 'long': + println('val = buffer.readUInt32BE(offset); offset += 4;'); + break; + case 'longlong': + case 'timestamp': + println('val = ints.readUInt64BE(buffer, offset); offset += 8;'); + break; + case 'longstr': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = buffer.slice(offset, offset + len);'); + println('offset += len;'); + break; + case 'shortstr': + println('len = buffer.readUInt8(offset); offset++;'); + println('val = buffer.toString("utf8", offset, offset + len);'); + println('offset += len;'); + break; + case 'table': + println('len = buffer.readUInt32BE(offset); offset += 4;'); + println('val = decodeFields(buffer.slice(offset, offset + len));'); + println('offset += len;'); + break; + default: + throw new TypeError("Unexpected type in argument list: " + p.type); + } + println('%s = val;', field); + } + println('}'); + } + println('return fields;'); + println('}'); +} diff --git a/node_modules/amqplib/callback_api.js b/node_modules/amqplib/callback_api.js new file mode 100644 index 0000000..1955312 --- /dev/null +++ b/node_modules/amqplib/callback_api.js @@ -0,0 +1,22 @@ +var raw_connect = require('./lib/connect').connect; +var CallbackModel = require('./lib/callback_model').CallbackModel; + +// Supports three shapes: +// connect(url, options, callback) +// connect(url, callback) +// connect(callback) +function connect(url, options, cb) { + if (typeof url === 'function') + cb = url, url = false, options = false; + else if (typeof options === 'function') + cb = options, options = false; + + raw_connect(url, options, function(err, c) { + if (err === null) cb(null, new CallbackModel(c)); + else cb(err); + }); +}; + +module.exports.connect = connect; +module.exports.credentials = require('./lib/credentials'); +module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/channel_api.js b/node_modules/amqplib/channel_api.js new file mode 100644 index 0000000..6c8c4dd --- /dev/null +++ b/node_modules/amqplib/channel_api.js @@ -0,0 +1,16 @@ +var raw_connect = require('./lib/connect').connect; +var ChannelModel = require('./lib/channel_model').ChannelModel; +var Promise = require('bluebird'); + +function connect(url, connOptions) { + return Promise.fromCallback(function(cb) { + return raw_connect(url, connOptions, cb); + }) + .then(function(conn) { + return new ChannelModel(conn); + }); +}; + +module.exports.connect = connect; +module.exports.credentials = require('./lib/credentials'); +module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/examples/headers.js b/node_modules/amqplib/examples/headers.js new file mode 100644 index 0000000..e4f7bcc --- /dev/null +++ b/node_modules/amqplib/examples/headers.js @@ -0,0 +1,42 @@ +#!/usr/bin/env node + +// Example of using a headers exchange + +var amqp = require('../') + +amqp.connect().then(function(conn) { + return conn.createChannel().then(withChannel); +}, console.error); + +function withChannel(ch) { + // NB the type of the exchange is 'headers' + ch.assertExchange('matching exchange', 'headers').then(function(ex) { + ch.assertQueue().then(function(q) { + bindAndConsume(ch, ex, q).then(function() { + send(ch, ex); + }); + }); + }); +} + +function bindAndConsume(ch, ex, q) { + // When using a headers exchange, the headers to be matched go in + // the binding arguments. The routing key is ignore, so best left + // empty. + + // 'x-match' is 'all' or 'any', meaning "all fields must match" or + // "at least one field must match", respectively. The values to be + // matched go in subsequent fields. + ch.bindQueue(q.queue, ex.exchange, '', {'x-match': 'any', + 'foo': 'bar', + 'baz': 'boo'}); + return ch.consume(q.queue, function(msg) { + console.log(msg.content.toString()); + }, {noAck: true}); +} + +function send(ch, ex) { + // The headers for a message are given as an option to `publish`: + ch.publish(ex.exchange, '', Buffer.from('hello'), {headers: {baz: 'boo'}}); + ch.publish(ex.exchange, '', Buffer.from('world'), {headers: {foo: 'bar'}}); +} diff --git a/node_modules/amqplib/examples/receive_generator.js b/node_modules/amqplib/examples/receive_generator.js new file mode 100644 index 0000000..8146de0 --- /dev/null +++ b/node_modules/amqplib/examples/receive_generator.js @@ -0,0 +1,39 @@ +#!/usr/bin/env node + +'use strict'; +const co = require('co'); +const amqp = require('amqplib'); +const readline = require('readline'); + +co(function* () { + const myConsumer = (msg) => { + if (msg !== null) { + console.log('consuming message %s in generator', JSON.stringify(msg.content.toString())); + } + }; + const conn = yield amqp.connect('amqp://localhost'); + try { + // create a message to consume + const q = 'hello'; + const msg = 'Hello World!'; + const channel = yield conn.createChannel(); + yield channel.assertQueue(q); + channel.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + // consume the message + yield channel.consume(q, myConsumer, { noAck: true }); + } + catch (e) { + throw e; + } +}).catch(err => { + console.warn('Error:', err); +}); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +// pend until message is consumed +rl.question('newline to exit', () => process.exit()); \ No newline at end of file diff --git a/node_modules/amqplib/examples/send_generators.js b/node_modules/amqplib/examples/send_generators.js new file mode 100644 index 0000000..171778e --- /dev/null +++ b/node_modules/amqplib/examples/send_generators.js @@ -0,0 +1,42 @@ +#!/usr/bin/env node + +'use strict'; + +// NB this requires the module 'co': +// npm install co +const co = require('co'); +const amqp = require('amqplib'); + +co(function* () { + // connection errors are handled in the co .catch handler + const conn = yield amqp.connect('amqp://localhost'); + + // try catch will throw any errors from the yielding the following promises to the co .catch handler + try { + const q = 'hello'; + const msg = 'Hello World!'; + + // use a confirm channel so we can check the message is sent OK. + const channel = yield conn.createConfirmChannel(); + + yield channel.assertQueue(q); + + channel.sendToQueue(q, Buffer.from(msg)); + + // if message has been nacked, this will result in an error (rejected promise); + yield channel.waitForConfirms(); + + console.log(" [x] Sent '%s'", msg); + + channel.close(); + } + catch (e) { + throw e; + } + finally { + conn.close(); + } + +}).catch(err => { + console.warn('Error:', err); +}); diff --git a/node_modules/amqplib/examples/ssl.js b/node_modules/amqplib/examples/ssl.js new file mode 100644 index 0000000..07f1ae1 --- /dev/null +++ b/node_modules/amqplib/examples/ssl.js @@ -0,0 +1,64 @@ +// Example of using a TLS/SSL connection. Note that the server must be +// configured to accept SSL connections; see, for example, +// http://www.rabbitmq.com/ssl.html. +// +// When trying this out, I followed the RabbitMQ SSL guide above, +// almost verbatim. I set the CN of the server certificate to +// 'localhost' rather than $(hostname) (since on my MBP hostname ends +// up being ".local", which is just weird). My client +// certificates etc., are in `../etc/client/`. My testca certificate +// is in `../etc/testca` and server certs etc., in `../etc/server`, +// and I've made a `rabbitmq.config` file, with which I start +// RabbitMQ: +// +// RABBITMQ_CONFIG_FILE=`pwd`/../etc/server/rabbitmq \ +// /usr/local/sbin/rabbitmq-server & +// +// A way to check RabbitMQ's running with SSL OK is to use +// +// openssl s_client -connect localhost:5671 + +var amqp = require('../'); +var fs = require('fs'); + +// Assemble the SSL options; for verification we need at least +// * a certificate to present to the server ('cert', in PEM format) +// * the private key for the certificate ('key', in PEM format) +// * (possibly) a passphrase for the private key +// +// The first two may be replaced with a PKCS12 file ('pfx', in pkcs12 +// format) + +// We will also want to list the CA certificates that we will trust, +// since we're using a self-signed certificate. It is NOT recommended +// to use `rejectUnauthorized: false`. + +// Options for full client and server verification: +var opts = { + cert: fs.readFileSync('../etc/client/cert.pem'), + key: fs.readFileSync('../etc/client/key.pem'), + // cert and key or + // pfx: fs.readFileSync('../etc/client/keycert.p12'), + passphrase: 'MySecretPassword', + ca: [fs.readFileSync('../etc/testca/cacert.pem')] +}; + +// Options for just confidentiality. This requires RabbitMQ's SSL +// configuration to include the items +// +// {verify, verify_none}, +// {fail_if_no_peer_cert,false} +// +// var opts = { ca: [fs.readFileSync('../etc/testca/cacert.pem')] }; + +// Option to use the SSL client certificate for authentication +// opts.credentials = amqp.credentials.external(); + +var open = amqp.connect('amqps://localhost', opts); + +open.then(function(conn) { + process.on('SIGINT', conn.close.bind(conn)); + return conn.createChannel().then(function(ch) { + ch.sendToQueue('foo', Buffer.from('Hello World!')); + }); +}).then(null, console.warn); diff --git a/node_modules/amqplib/examples/tutorials/README.md b/node_modules/amqplib/examples/tutorials/README.md new file mode 100644 index 0000000..333fda3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/README.md @@ -0,0 +1,93 @@ +# RabbitMQ tutorials + +This directory contains the [RabbitMQ tutorials][rabbitmq-tutes], +ported to amqplib. The sub-directory `callback_api` has translations +of the tutorial programs to the callback-oriented API. + +## Preparation + +To run the tutorial code, you need amqplib installed. Assuming you are +in a clone of the amqplib repository, from the tutorials directory: + + npm install + +or to use the latest released version, + + npm install amqplib + +Then just run each file as a script, e.g., in bash + + ./send.js + +or + + node send.js + +or + + nave use 0.8 node send.js + +## [Tutorial one: Hello World!][tute-one] + +A "Hello World" example, with one script sending a message to a queue, +and another receiving messages from the same queue. + + * [send.js](send.js) + * [receive.js](receive.js) + +## [Tutorial two: Work queues][tute-two] + +Using RabbitMQ as a work queue; `new_task` creates a task, and +`worker` processes tasks. Multiple `worker` process will share the +tasks among them. Long-running tasks are simulated by supplying a +string with dots, e.g., '...' to `new_task`. Each dot makes the worker +"work" for a second. + + * [new_task.js](new_task.js) + * [worker.js](worker.js) + +## [Tutorial three: Publish/Subscribe][tute-three] + +Using RabbitMQ as a broadcast mechanism. `emit_log` sends a "log" +message to a fanout exchange, and all `receive_logs` processes receive +log messages. + + * [emit_log.js](emit_log.js) + * [receive_logs.js](receive_logs.js) + +## [Tutorial four: Routing][tute-four] + +Using RabbitMQ as a routing ('somecast') mechanism. `emit_log_direct` +sends a log message with a severity, and all `receive_logs_direct` +processes receive log messages for the severities on which they are +listening. + + * [emit_log_direct.js](emit_log_direct.js) + * [receive_logs_direct.js](receive_logs_direct.js) + +## [Tutorial five: Topics][tute-five] + +Extends the previous tutorial to routing with wildcarded patterns. + + * [emit_log_topic.js](emit_log_topic.js) + * [receive_logs_topic.js](receive_logs_topic.js) + +## [Tutorial six: RPC][tute-six] + +Using RabbitMQ as an RPC intermediary, queueing requests for servers +and routing replies back to clients. + + * [rpc_server.js](rpc_server.js) + * [rpc_client.js](rpc_client.js) + +I depart slightly from the original tutorial code, which I think has +some needless object-orientation (in the Python code; you don't get a +choice about needless object-orientation in Java). + +[rabbitmq-tutes]: http://github.com/rabbitmq/rabbitmq-tutorials +[tute-one]: http://www.rabbitmq.com/tutorials/tutorial-one-python.html +[tute-two]: http://www.rabbitmq.com/tutorials/tutorial-two-python.html +[tute-three]: http://www.rabbitmq.com/tutorials/tutorial-three-python.html +[tute-four]: http://www.rabbitmq.com/tutorials/tutorial-four-python.html +[tute-five]: http://www.rabbitmq.com/tutorials/tutorial-five-python.html +[tute-six]: http://www.rabbitmq.com/tutorials/tutorial-six-python.html diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js new file mode 100644 index 0000000..9ea353d --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var ex = 'logs'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertExchange(ex, 'fanout', {durable: false}); + var msg = process.argv.slice(2).join(' ') || + 'info: Hello World!'; + ch.publish(ex, '', Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js new file mode 100644 index 0000000..bd4e640 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var args = process.argv.slice(2); +var severity = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var ex = 'direct_logs'; + var exopts = {durable: false}; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertExchange(ex, 'direct', exopts, function(err, ok) { + ch.publish(ex, severity, Buffer.from(message)); + ch.close(function() { conn.close(); }); + }); + } + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js new file mode 100644 index 0000000..7601ecf --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js @@ -0,0 +1,27 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var args = process.argv.slice(2); +var key = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + var ex = 'topic_logs', exopts = {durable: false}; + conn.createChannel(function(err, ch) { + ch.assertExchange(ex, 'topic', exopts, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.publish(ex, key, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", key, message); + ch.close(function() { conn.close(); }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/new_task.js b/node_modules/amqplib/examples/tutorials/callback_api/new_task.js new file mode 100644 index 0000000..6122231 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/new_task.js @@ -0,0 +1,27 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var q = 'task_queue'; + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: true}, function(err, _ok) { + if (err !== null) return bail(err, conn); + var msg = process.argv.slice(2).join(' ') || "Hello World!"; + ch.sendToQueue(q, Buffer.from(msg), {persistent: true}); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive.js b/node_modules/amqplib/examples/tutorials/callback_api/receive.js new file mode 100644 index 0000000..c6bb056 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var q = 'hello'; + + function on_channel_open(err, ch) { + ch.assertQueue(q, {durable: false}, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.consume(q, function(msg) { // message callback + console.log(" [x] Received '%s'", msg.content.toString()); + }, {noAck: true}, function(_consumeOk) { // consume callback + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + }); + }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js new file mode 100644 index 0000000..4d024e4 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var ex = 'logs'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + var q = ok.queue; + ch.bindQueue(q, ex, ''); + ch.consume(q, logMessage, {noAck: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + console.log(" [*] Waiting for logs. To exit press CTRL+C."); + }); + }); + } + + function logMessage(msg) { + if (msg) + console.log(" [x] '%s'", msg.content.toString()); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js new file mode 100644 index 0000000..9bb9f98 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js @@ -0,0 +1,56 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var basename = require('path').basename; + +var severities = process.argv.slice(2); +if (severities.length < 1) { + console.log('Usage %s [info] [warning] [error]', + basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + var ex = 'direct_logs', exopts = {durable: false}; + + ch.assertExchange(ex, 'direct', exopts); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + + var queue = ok.queue, i = 0; + + function sub(err) { + if (err !== null) return bail(err, conn); + else if (i < severities.length) { + ch.bindQueue(queue, ex, severities[i], {}, sub); + i++; + } + } + + ch.consume(queue, logMessage, {noAck: true}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + sub(null); + }); + }); + }); +} + +function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js new file mode 100644 index 0000000..2c827c2 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); +var basename = require('path').basename; + +var keys = process.argv.slice(2); +if (keys.length < 1) { + console.log('Usage %s pattern [pattern...]', + basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + var ex = 'topic_logs', exopts = {durable: false}; + + ch.assertExchange(ex, 'topic', exopts); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + + var queue = ok.queue, i = 0; + + function sub(err) { + if (err !== null) return bail(err, conn); + else if (i < keys.length) { + ch.bindQueue(queue, ex, keys[i], {}, sub); + i++; + } + } + + ch.consume(queue, logMessage, {noAck: true}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + sub(null); + }); + }); + }); +} + +function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js new file mode 100644 index 0000000..abf22a0 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js @@ -0,0 +1,49 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); +var basename = require('path').basename; +var uuid = require('node-uuid'); + +var n; +try { + if (process.argv.length < 3) throw Error('Too few args'); + n = parseInt(process.argv[2]); +} +catch (e) { + console.error(e); + console.warn('Usage: %s number', basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + + var correlationId = uuid(); + function maybeAnswer(msg) { + if (msg.properties.correlationId === correlationId) { + console.log(' [.] Got %d', msg.content.toString()); + } + else return bail(new Error('Unexpected message'), conn); + ch.close(function() { conn.close(); }); + } + + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + var queue = ok.queue; + ch.consume(queue, maybeAnswer, {noAck:true}); + console.log(' [x] Requesting fib(%d)', n); + ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { + replyTo: queue, correlationId: correlationId + }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js new file mode 100644 index 0000000..dae1d9b --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function fib(n) { + var a = 0, b = 1; + for (var i=0; i < n; i++) { + var c = a + b; + a = b; b = c; + } + return a; +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + process.once('SIGINT', function() { conn.close(); }); + + var q = 'rpc_queue'; + + conn.createChannel(function(err, ch) { + ch.assertQueue(q, {durable: false}); + ch.prefetch(1); + ch.consume(q, reply, {noAck:false}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [x] Awaiting RPC requests'); + }); + + function reply(msg) { + var n = parseInt(msg.content.toString()); + console.log(' [.] fib(%d)', n); + ch.sendToQueue(msg.properties.replyTo, + Buffer.from(fib(n).toString()), + {correlationId: msg.properties.correlationId}); + ch.ack(msg); + } + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/send.js b/node_modules/amqplib/examples/tutorials/callback_api/send.js new file mode 100644 index 0000000..8ff0e4b --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/send.js @@ -0,0 +1,29 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var q = 'hello'; + var msg = 'Hello World!'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: false}, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/worker.js b/node_modules/amqplib/examples/tutorials/callback_api/worker.js new file mode 100644 index 0000000..ad7d076 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/worker.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var q = 'task_queue'; + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: true}, function(err, _ok) { + ch.consume(q, doWork, {noAck: false}); + console.log(" [*] Waiting for messages. To exit press CTRL+C"); + }); + + function doWork(msg) { + var body = msg.content.toString(); + console.log(" [x] Received '%s'", body); + var secs = body.split('.').length - 1; + setTimeout(function() { + console.log(" [x] Done"); + ch.ack(msg); + }, secs * 1000); + } + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/emit_log.js b/node_modules/amqplib/examples/tutorials/emit_log.js new file mode 100644 index 0000000..2bf7e14 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'logs'; + var ok = ch.assertExchange(ex, 'fanout', {durable: false}) + + var message = process.argv.slice(2).join(' ') || + 'info: Hello World!'; + + return ok.then(function() { + ch.publish(ex, '', Buffer.from(message)); + console.log(" [x] Sent '%s'", message); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/emit_log_direct.js new file mode 100644 index 0000000..0846edf --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log_direct.js @@ -0,0 +1,20 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +var args = process.argv.slice(2); +var severity = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'direct_logs'; + var ok = ch.assertExchange(ex, 'direct', {durable: false}); + + return ok.then(function() { + ch.publish(ex, severity, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", severity, message); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/emit_log_topic.js new file mode 100644 index 0000000..5f643a3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log_topic.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +var args = process.argv.slice(2); +var key = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'topic_logs'; + var ok = ch.assertExchange(ex, 'topic', {durable: false}); + return ok.then(function() { + ch.publish(ex, key, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", key, message); + return ch.close(); + }); + }).finally(function() { conn.close(); }) +}).catch(console.log); diff --git a/node_modules/amqplib/examples/tutorials/new_task.js b/node_modules/amqplib/examples/tutorials/new_task.js new file mode 100644 index 0000000..c25cfbc --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/new_task.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node +// Post a new task to the work queue + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var q = 'task_queue'; + var ok = ch.assertQueue(q, {durable: true}); + + return ok.then(function() { + var msg = process.argv.slice(2).join(' ') || "Hello World!"; + ch.sendToQueue(q, Buffer.from(msg), {deliveryMode: true}); + console.log(" [x] Sent '%s'", msg); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/package.json b/node_modules/amqplib/examples/tutorials/package.json new file mode 100644 index 0000000..e931546 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/package.json @@ -0,0 +1,16 @@ +{ + "name": "amqplib-tutorials", + "version": "0.0.1", + "description": "The RabbitMQ tutorials, ported to amqplib", + "main": "send.js", + "dependencies": { + "amqplib": "../..", + "uuid": "*" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": "", + "author": "Michael Bridgen ", + "license": "MPL 2.0" +} diff --git a/node_modules/amqplib/examples/tutorials/receive.js b/node_modules/amqplib/examples/tutorials/receive.js new file mode 100644 index 0000000..b7a7975 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive.js @@ -0,0 +1,21 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + + var ok = ch.assertQueue('hello', {durable: false}); + + ok = ok.then(function(_qok) { + return ch.consume('hello', function(msg) { + console.log(" [x] Received '%s'", msg.content.toString()); + }, {noAck: true}); + }); + + return ok.then(function(_consumeOk) { + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + }); + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs.js b/node_modules/amqplib/examples/tutorials/receive_logs.js new file mode 100644 index 0000000..d592af9 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ok = ch.assertExchange('logs', 'fanout', {durable: false}); + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + ok = ok.then(function(qok) { + return ch.bindQueue(qok.queue, 'logs', '').then(function() { + return qok.queue; + }); + }); + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C'); + }); + + function logMessage(msg) { + console.log(" [x] '%s'", msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/receive_logs_direct.js new file mode 100644 index 0000000..17fc22d --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs_direct.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var all = require('bluebird').all; +var basename = require('path').basename; + +var severities = process.argv.slice(2); +if (severities.length < 1) { + console.warn('Usage: %s [info] [warning] [error]', + basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ex = 'direct_logs'; + + var ok = ch.assertExchange(ex, 'direct', {durable: false}); + + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + + ok = ok.then(function(qok) { + var queue = qok.queue; + return all(severities.map(function(sev) { + ch.bindQueue(queue, ex, sev); + })).then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }); + + function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/receive_logs_topic.js new file mode 100644 index 0000000..3e8eb6f --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs_topic.js @@ -0,0 +1,44 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var basename = require('path').basename; +var all = require('bluebird').all; + +var keys = process.argv.slice(2); +if (keys.length < 1) { + console.log('Usage: %s pattern [pattern...]', + basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ex = 'topic_logs'; + var ok = ch.assertExchange(ex, 'topic', {durable: false}); + + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + + ok = ok.then(function(qok) { + var queue = qok.queue; + return all(keys.map(function(rk) { + ch.bindQueue(queue, ex, rk); + })).then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }); + + function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_client.js b/node_modules/amqplib/examples/tutorials/rpc_client.js new file mode 100644 index 0000000..47566b3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/rpc_client.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var basename = require('path').basename; +var Promise = require('bluebird'); +var uuid = require('node-uuid'); + +// I've departed from the form of the original RPC tutorial, which +// needlessly introduces a class definition, and doesn't even +// parameterise the request. + +var n; +try { + if (process.argv.length < 3) throw Error('Too few args'); + n = parseInt(process.argv[2]); +} +catch (e) { + console.error(e); + console.warn('Usage: %s number', basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + return new Promise(function(resolve) { + var corrId = uuid(); + function maybeAnswer(msg) { + if (msg.properties.correlationId === corrId) { + resolve(msg.content.toString()); + } + } + + var ok = ch.assertQueue('', {exclusive: true}) + .then(function(qok) { return qok.queue; }); + + ok = ok.then(function(queue) { + return ch.consume(queue, maybeAnswer, {noAck: true}) + .then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + console.log(' [x] Requesting fib(%d)', n); + ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { + correlationId: corrId, replyTo: queue + }); + }); + }); + }) + .then(function(fibN) { + console.log(' [.] Got %d', fibN); + }) + .finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_server.js b/node_modules/amqplib/examples/tutorials/rpc_server.js new file mode 100644 index 0000000..84101ce --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/rpc_server.js @@ -0,0 +1,39 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +function fib(n) { + // Do it the ridiculous, but not most ridiculous, way. For better, + // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms + var a = 0, b = 1; + for (var i=0; i < n; i++) { + var c = a + b; + a = b; b = c; + } + return a; +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var q = 'rpc_queue'; + var ok = ch.assertQueue(q, {durable: false}); + var ok = ok.then(function() { + ch.prefetch(1); + return ch.consume(q, reply); + }); + return ok.then(function() { + console.log(' [x] Awaiting RPC requests'); + }); + + function reply(msg) { + var n = parseInt(msg.content.toString()); + console.log(' [.] fib(%d)', n); + var response = fib(n); + ch.sendToQueue(msg.properties.replyTo, + Buffer.from(response.toString()), + {correlationId: msg.properties.correlationId}); + ch.ack(msg); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/send.js b/node_modules/amqplib/examples/tutorials/send.js new file mode 100644 index 0000000..59f846e --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/send.js @@ -0,0 +1,23 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var q = 'hello'; + var msg = 'Hello World!'; + + var ok = ch.assertQueue(q, {durable: false}); + + return ok.then(function(_qok) { + // NB: `sentToQueue` and `publish` both return a boolean + // indicating whether it's OK to send again straight away, or + // (when `false`) that you should wait for the event `'drain'` + // to fire before writing again. We're just doing the one write, + // so we'll ignore it. + ch.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/worker.js b/node_modules/amqplib/examples/tutorials/worker.js new file mode 100644 index 0000000..fdb72df --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/worker.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node +// Process tasks from the work queue + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ok = ch.assertQueue('task_queue', {durable: true}); + ok = ok.then(function() { ch.prefetch(1); }); + ok = ok.then(function() { + ch.consume('task_queue', doWork, {noAck: false}); + console.log(" [*] Waiting for messages. To exit press CTRL+C"); + }); + return ok; + + function doWork(msg) { + var body = msg.content.toString(); + console.log(" [x] Received '%s'", body); + var secs = body.split('.').length - 1; + //console.log(" [x] Task takes %d seconds", secs); + setTimeout(function() { + console.log(" [x] Done"); + ch.ack(msg); + }, secs * 1000); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/waitForConfirms.js b/node_modules/amqplib/examples/waitForConfirms.js new file mode 100644 index 0000000..d16a1d8 --- /dev/null +++ b/node_modules/amqplib/examples/waitForConfirms.js @@ -0,0 +1,22 @@ +var amqp = require('../'); + +var NUM_MSGS = 20; + +function mkCallback(i) { + return (i % 2) === 0 ? function(err) { + if (err !== null) { console.error('Message %d failed!', i); } + else { console.log('Message %d confirmed', i); } + } : null; +} + +amqp.connect().then(function(c) { + c.createConfirmChannel().then(function(ch) { + for (var i=0; i < NUM_MSGS; i++) { + ch.publish('amq.topic', 'whatever', Buffer.from('blah'), {}, mkCallback(i)); + } + ch.waitForConfirms().then(function() { + console.log('All messages done'); + c.close(); + }).catch(console.error); + }); +}); diff --git a/node_modules/amqplib/lib/api_args.js b/node_modules/amqplib/lib/api_args.js new file mode 100644 index 0000000..740fe87 --- /dev/null +++ b/node_modules/amqplib/lib/api_args.js @@ -0,0 +1,314 @@ +// +// +// + +'use strict'; + +/* +The channel (promise) and callback APIs have similar signatures, and +in particular, both need AMQP fields prepared from the same arguments +and options. The arguments marshalling is done here. Each of the +procedures below takes arguments and options (the latter in an object) +particular to the operation it represents, and returns an object with +fields for handing to the encoder. +*/ + +// A number of AMQP methods have a table-typed field called +// `arguments`, that is intended to carry extension-specific +// values. RabbitMQ uses this in a number of places; e.g., to specify +// an 'alternate exchange'. +// +// Many of the methods in this API have an `options` argument, from +// which I take both values that have a default in AMQP (e.g., +// autoDelete in QueueDeclare) *and* values that are specific to +// RabbitMQ (e.g., 'alternate-exchange'), which would normally be +// supplied in `arguments`. So that extensions I don't support yet can +// be used, I include `arguments` itself among the options. +// +// The upshot of this is that I often need to prepare an `arguments` +// value that has any values passed in `options.arguments` as well as +// any I've promoted to being options themselves. Since I don't want +// to mutate anything passed in, the general pattern is to create a +// fresh object with the `arguments` value given as its prototype; all +// fields in the supplied value will be serialised, as well as any I +// set on the fresh object. What I don't want to do, however, is set a +// field to undefined by copying possibly missing field values, +// because that will mask a value in the prototype. +// +// NB the `arguments` field already has a default value of `{}`, so +// there's no need to explicitly default it unless I'm setting values. +function setIfDefined(obj, prop, value) { + if (value != undefined) obj[prop] = value; +} + +var EMPTY_OPTIONS = Object.freeze({}); + +var Args = {}; + +Args.assertQueue = function(queue, options) { + queue = queue || ''; + options = options || EMPTY_OPTIONS; + + var argt = Object.create(options.arguments || null); + setIfDefined(argt, 'x-expires', options.expires); + setIfDefined(argt, 'x-message-ttl', options.messageTtl); + setIfDefined(argt, 'x-dead-letter-exchange', + options.deadLetterExchange); + setIfDefined(argt, 'x-dead-letter-routing-key', + options.deadLetterRoutingKey); + setIfDefined(argt, 'x-max-length', options.maxLength); + setIfDefined(argt, 'x-max-priority', options.maxPriority); + setIfDefined(argt, 'x-overflow', options.overflow); + setIfDefined(argt, 'x-queue-mode', options.queueMode); + + return { + queue: queue, + exclusive: !!options.exclusive, + durable: (options.durable === undefined) ? true : options.durable, + autoDelete: !!options.autoDelete, + arguments: argt, + passive: false, + // deprecated but we have to include it + ticket: 0, + nowait: false + }; +}; + +Args.checkQueue = function(queue) { + return { + queue: queue, + passive: true, // switch to "completely different" mode + nowait: false, + durable: true, autoDelete: false, exclusive: false, // ignored + ticket: 0, + }; +}; + +Args.deleteQueue = function(queue, options) { + options = options || EMPTY_OPTIONS; + return { + queue: queue, + ifUnused: !!options.ifUnused, + ifEmpty: !!options.ifEmpty, + ticket: 0, nowait: false + }; +}; + +Args.purgeQueue = function(queue) { + return { + queue: queue, + ticket: 0, nowait: false + }; +}; + +Args.bindQueue = function(queue, source, pattern, argt) { + return { + queue: queue, + exchange: source, + routingKey: pattern, + arguments: argt, + ticket: 0, nowait: false + }; +}; + +Args.unbindQueue = function(queue, source, pattern, argt) { + return { + queue: queue, + exchange: source, + routingKey: pattern, + arguments: argt, + ticket: 0, nowait: false + }; +}; + +Args.assertExchange = function(exchange, type, options) { + options = options || EMPTY_OPTIONS; + var argt = Object.create(options.arguments || null); + setIfDefined(argt, 'alternate-exchange', options.alternateExchange); + return { + exchange: exchange, + ticket: 0, + type: type, + passive: false, + durable: (options.durable === undefined) ? true : options.durable, + autoDelete: !!options.autoDelete, + internal: !!options.internal, + nowait: false, + arguments: argt + }; +}; + +Args.checkExchange = function(exchange) { + return { + exchange: exchange, + passive: true, // switch to 'may as well be another method' mode + nowait: false, + // ff are ignored + durable: true, internal: false, type: '', autoDelete: false, + ticket: 0 + }; +}; + +Args.deleteExchange = function(exchange, options) { + options = options || EMPTY_OPTIONS; + return { + exchange: exchange, + ifUnused: !!options.ifUnused, + ticket: 0, nowait: false + }; +}; + +Args.bindExchange = function(dest, source, pattern, argt) { + return { + source: source, + destination: dest, + routingKey: pattern, + arguments: argt, + ticket: 0, nowait: false + }; +}; + +Args.unbindExchange = function(dest, source, pattern, argt) { + return { + source: source, + destination: dest, + routingKey: pattern, + arguments: argt, + ticket: 0, nowait: false + }; +}; + +// It's convenient to construct the properties and the method fields +// at the same time, since in the APIs, values for both can appear in +// `options`. Since the property or mthod field names don't overlap, I +// just return one big object that can be used for both purposes, and +// the encoder will pick out what it wants. +Args.publish = function(exchange, routingKey, options) { + options = options || EMPTY_OPTIONS; + + // The CC and BCC fields expect an array of "longstr", which would + // normally be buffer values in JavaScript; however, since a field + // array (or table) cannot have shortstr values, the codec will + // encode all strings as longstrs anyway. + function convertCC(cc) { + if (cc === undefined) { + return undefined; + } + else if (Array.isArray(cc)) { + return cc.map(String); + } + else return [String(cc)]; + } + + var headers = Object.create(options.headers || null); + setIfDefined(headers, 'CC', convertCC(options.CC)); + setIfDefined(headers, 'BCC', convertCC(options.BCC)); + + var deliveryMode; // undefined will default to 1 (non-persistent) + + // Previously I overloaded deliveryMode be a boolean meaning + // 'persistent or not'; better is to name this option for what it + // is, but I need to have backwards compatibility for applications + // that either supply a numeric or boolean value. + if (options.persistent !== undefined) + deliveryMode = (options.persistent) ? 2 : 1; + else if (typeof options.deliveryMode === 'number') + deliveryMode = options.deliveryMode; + else if (options.deliveryMode) // is supplied and truthy + deliveryMode = 2; + + var expiration = options.expiration; + if (expiration !== undefined) expiration = expiration.toString(); + + return { + // method fields + exchange: exchange, + routingKey: routingKey, + mandatory: !!options.mandatory, + immediate: false, // RabbitMQ doesn't implement this any more + ticket: undefined, + // properties + contentType: options.contentType, + contentEncoding: options.contentEncoding, + headers: headers, + deliveryMode: deliveryMode, + priority: options.priority, + correlationId: options.correlationId, + replyTo: options.replyTo, + expiration: expiration, + messageId: options.messageId, + timestamp: options.timestamp, + type: options.type, + userId: options.userId, + appId: options.appId, + clusterId: undefined + }; +}; + +Args.consume = function(queue, options) { + options = options || EMPTY_OPTIONS; + var argt = Object.create(options.arguments || null); + setIfDefined(argt, 'x-priority', options.priority); + return { + ticket: 0, + queue: queue, + consumerTag: options.consumerTag || '', + noLocal: !!options.noLocal, + noAck: !!options.noAck, + exclusive: !!options.exclusive, + nowait: false, + arguments: argt + }; +}; + +Args.cancel = function(consumerTag) { + return { + consumerTag: consumerTag, + nowait: false + }; +}; + +Args.get = function(queue, options) { + options = options || EMPTY_OPTIONS; + return { + ticket: 0, + queue: queue, + noAck: !!options.noAck + }; +}; + +Args.ack = function(tag, allUpTo) { + return { + deliveryTag: tag, + multiple: !!allUpTo + }; +}; + +Args.nack = function(tag, allUpTo, requeue) { + return { + deliveryTag: tag, + multiple: !!allUpTo, + requeue: (requeue === undefined) ? true : requeue + }; +}; + +Args.reject = function(tag, requeue) { + return { + deliveryTag: tag, + requeue: (requeue === undefined) ? true : requeue + }; +}; + +Args.prefetch = function(count, global) { + return { + prefetchCount: count || 0, + prefetchSize: 0, + global: !!global + }; +}; + +Args.recover = function() { + return {requeue: true}; +}; + +module.exports = Object.freeze(Args); diff --git a/node_modules/amqplib/lib/bitset.js b/node_modules/amqplib/lib/bitset.js new file mode 100644 index 0000000..61f586b --- /dev/null +++ b/node_modules/amqplib/lib/bitset.js @@ -0,0 +1,103 @@ +// +// +// + +// A bitset implementation, after that in java.util. Yes there +// already exist such things, but none implement next{Clear|Set}Bit or +// equivalent, and none involved me tooling about for an evening. + +'use strict'; + +function BitSet(size) { + if (size) { + var numWords = Math.ceil(size / 32); + this.words = new Array(numWords); + } + else { + this.words = []; + } + this.wordsInUse = 0; // = number, not index +} + +var P = BitSet.prototype; + +function wordIndex(bitIndex) { + return Math.floor(bitIndex / 32); +} + +// Make sure we have at least numWords +P.ensureSize = function(numWords) { + var wordsPresent = this.words.length; + if (wordsPresent < numWords) { + this.words = this.words.concat(new Array(numWords - wordsPresent)); + } +} + +P.set = function(bitIndex) { + var w = wordIndex(bitIndex); + if (w >= this.wordsInUse) { + this.ensureSize(w + 1); + this.wordsInUse = w + 1; + } + var bit = 1 << bitIndex; + this.words[w] |= bit; +}; + +P.clear = function(bitIndex) { + var w = wordIndex(bitIndex); + if (w >= this.wordsInUse) return; + var mask = ~(1 << bitIndex); + this.words[w] &= mask; +}; + +P.get = function(bitIndex) { + var w = wordIndex(bitIndex); + if (w >= this.wordsInUse) return false; // >= since index vs size + var bit = 1 << bitIndex; + return !!(this.words[w] & bit); +} + +function trailingZeros(i) { + // From Hacker's Delight, via JDK. Probably far less effective here, + // since bit ops are not necessarily the quick way to do things in + // JS. + if (i === 0) return 32; + var y, n = 31; + y = i << 16; if (y != 0) { n = n -16; i = y; } + y = i << 8; if (y != 0) { n = n - 8; i = y; } + y = i << 4; if (y != 0) { n = n - 4; i = y; } + y = i << 2; if (y != 0) { n = n - 2; i = y; } + return n - ((i << 1) >>> 31); +} + +// Give the next bit that's set on or after fromIndex, or -1 if no such +// bit +P.nextSetBit = function(fromIndex) { + var w = wordIndex(fromIndex); + if (w >= this.wordsInUse) return -1; + + // the right-hand side is shifted to only test the bits of the first + // word that are > fromIndex + var word = this.words[w] & (0xffffffff << fromIndex); + while (true) { + if (word) return (w * 32) + trailingZeros(word); + w++; + if (w === this.wordsInUse) return -1; + word = this.words[w]; + } +}; + +P.nextClearBit = function(fromIndex) { + var w = wordIndex(fromIndex); + if (w >= this.wordsInUse) return fromIndex; + + var word = ~(this.words[w]) & (0xffffffff << fromIndex); + while (true) { + if (word) return (w * 32) + trailingZeros(word); + w++; + if (w == this.wordsInUse) return w * 32; + word = ~(this.words[w]); + } +}; + +module.exports.BitSet = BitSet; diff --git a/node_modules/amqplib/lib/callback_model.js b/node_modules/amqplib/lib/callback_model.js new file mode 100644 index 0000000..dca383f --- /dev/null +++ b/node_modules/amqplib/lib/callback_model.js @@ -0,0 +1,328 @@ +// +// +// + +'use strict'; + +var defs = require('./defs'); +var Promise = require('bluebird'); +var inherits = require('util').inherits; +var EventEmitter = require('events').EventEmitter; +var BaseChannel = require('./channel').BaseChannel; +var acceptMessage = require('./channel').acceptMessage; +var Args = require('./api_args'); + +function CallbackModel(connection) { + if (!(this instanceof CallbackModel)) + return new CallbackModel(connection); + EventEmitter.call( this ); + this.connection = connection; + var self = this; + ['error', 'close', 'blocked', 'unblocked'].forEach(function(ev) { + connection.on(ev, self.emit.bind(self, ev)); + }); +} +inherits(CallbackModel, EventEmitter); + +module.exports.CallbackModel = CallbackModel; + +CallbackModel.prototype.close = function(cb) { + this.connection.close(cb); +}; + +function Channel(connection) { + BaseChannel.call(this, connection); + this.on('delivery', this.handleDelivery.bind(this)); + this.on('cancel', this.handleCancel.bind(this)); +} +inherits(Channel, BaseChannel); + +module.exports.Channel = Channel; + +CallbackModel.prototype.createChannel = function(cb) { + var ch = new Channel(this.connection); + ch.open(function(err, ok) { + if (err === null) cb && cb(null, ch); + else cb && cb(err); + }); + return ch; +}; + +// Wrap an RPC callback to make sure the callback is invoked with +// either `(null, value)` or `(error)`, i.e., never two non-null +// values. Also substitutes a stub if the callback is `undefined` or +// otherwise falsey, for convenience in methods for which the callback +// is optional (that is, most of them). +function callbackWrapper(ch, cb) { + return (cb) ? function(err, ok) { + if (err === null) { + cb(null, ok); + } + else cb(err); + } : function() {}; +} + +// This encodes straight-forward RPC: no side-effects and return the +// fields from the server response. It wraps the callback given it, so +// the calling method argument can be passed as-is. For anything that +// needs to have side-effects, or needs to change the server response, +// use `#_rpc(...)` and remember to dereference `.fields` of the +// server response. +Channel.prototype.rpc = function(method, fields, expect, cb0) { + var cb = callbackWrapper(this, cb0); + this._rpc(method, fields, expect, function(err, ok) { + cb(err, ok && ok.fields); // in case of an error, ok will be + // undefined + }); + return this; +}; + +// === Public API === + +Channel.prototype.open = function(cb) { + try { this.allocate(); } + catch (e) { return cb(e); } + + return this.rpc(defs.ChannelOpen, {outOfBand: ""}, + defs.ChannelOpenOk, cb); +}; + +Channel.prototype.close = function(cb) { + return this.closeBecause("Goodbye", defs.constants.REPLY_SUCCESS, + function() { cb && cb(null); }); +}; + +Channel.prototype.assertQueue = function(queue, options, cb) { + return this.rpc(defs.QueueDeclare, + Args.assertQueue(queue, options), + defs.QueueDeclareOk, cb); +}; + +Channel.prototype.checkQueue = function(queue, cb) { + return this.rpc(defs.QueueDeclare, + Args.checkQueue(queue), + defs.QueueDeclareOk, cb); +}; + +Channel.prototype.deleteQueue = function(queue, options, cb) { + return this.rpc(defs.QueueDelete, + Args.deleteQueue(queue, options), + defs.QueueDeleteOk, cb); +}; + +Channel.prototype.purgeQueue = function(queue, cb) { + return this.rpc(defs.QueuePurge, + Args.purgeQueue(queue), + defs.QueuePurgeOk, cb); +}; + +Channel.prototype.bindQueue = + function(queue, source, pattern, argt, cb) { + return this.rpc(defs.QueueBind, + Args.bindQueue(queue, source, pattern, argt), + defs.QueueBindOk, cb); + }; + +Channel.prototype.unbindQueue = + function(queue, source, pattern, argt, cb) { + return this.rpc(defs.QueueUnbind, + Args.unbindQueue(queue, source, pattern, argt), + defs.QueueUnbindOk, cb); + }; + +Channel.prototype.assertExchange = function(ex, type, options, cb0) { + var cb = callbackWrapper(this, cb0); + this._rpc(defs.ExchangeDeclare, + Args.assertExchange(ex, type, options), + defs.ExchangeDeclareOk, + function(e, _) { cb(e, {exchange: ex}); }); + return this; +}; + +Channel.prototype.checkExchange = function(exchange, cb) { + return this.rpc(defs.ExchangeDeclare, + Args.checkExchange(exchange), + defs.ExchangeDeclareOk, cb); +}; + +Channel.prototype.deleteExchange = function(exchange, options, cb) { + return this.rpc(defs.ExchangeDelete, + Args.deleteExchange(exchange, options), + defs.ExchangeDeleteOk, cb); +}; + +Channel.prototype.bindExchange = + function(dest, source, pattern, argt, cb) { + return this.rpc(defs.ExchangeBind, + Args.bindExchange(dest, source, pattern, argt), + defs.ExchangeBindOk, cb); + }; + +Channel.prototype.unbindExchange = + function(dest, source, pattern, argt, cb) { + return this.rpc(defs.ExchangeUnbind, + Args.unbindExchange(dest, source, pattern, argt), + defs.ExchangeUnbindOk, cb); + }; + +Channel.prototype.publish = + function(exchange, routingKey, content, options) { + var fieldsAndProps = Args.publish(exchange, routingKey, options); + return this.sendMessage(fieldsAndProps, fieldsAndProps, content); + }; + +Channel.prototype.sendToQueue = function(queue, content, options) { + return this.publish('', queue, content, options); +}; + +Channel.prototype.consume = function(queue, callback, options, cb0) { + var cb = callbackWrapper(this, cb0); + var fields = Args.consume(queue, options); + var self = this; + this._rpc( + defs.BasicConsume, fields, defs.BasicConsumeOk, + function(err, ok) { + if (err === null) { + self.registerConsumer(ok.fields.consumerTag, callback); + cb(null, ok.fields); + } + else cb(err); + }); + return this; +}; + +Channel.prototype.cancel = function(consumerTag, cb0) { + var cb = callbackWrapper(this, cb0); + var self = this; + this._rpc( + defs.BasicCancel, Args.cancel(consumerTag), defs.BasicCancelOk, + function(err, ok) { + if (err === null) { + self.unregisterConsumer(consumerTag); + cb(null, ok.fields); + } + else cb(err); + }); + return this; +}; + +Channel.prototype.get = function(queue, options, cb0) { + var self = this; + var fields = Args.get(queue, options); + var cb = callbackWrapper(this, cb0); + this.sendOrEnqueue(defs.BasicGet, fields, function(err, f) { + if (err === null) { + if (f.id === defs.BasicGetEmpty) { + cb(null, false); + } + else if (f.id === defs.BasicGetOk) { + self.handleMessage = acceptMessage(function(m) { + m.fields = f.fields; + cb(null, m); + }); + } + else { + cb(new Error("Unexpected response to BasicGet: " + + inspect(f))); + } + } + }); + return this; +}; + +Channel.prototype.ack = function(message, allUpTo) { + this.sendImmediately( + defs.BasicAck, Args.ack(message.fields.deliveryTag, allUpTo)); + return this; +}; + +Channel.prototype.ackAll = function() { + this.sendImmediately(defs.BasicAck, Args.ack(0, true)); + return this; +}; + +Channel.prototype.nack = function(message, allUpTo, requeue) { + this.sendImmediately( + defs.BasicNack, + Args.nack(message.fields.deliveryTag, allUpTo, requeue)); + return this; +}; + +Channel.prototype.nackAll = function(requeue) { + this.sendImmediately( + defs.BasicNack, Args.nack(0, true, requeue)) + return this; +}; + +Channel.prototype.reject = function(message, requeue) { + this.sendImmediately( + defs.BasicReject, + Args.reject(message.fields.deliveryTag, requeue)); + return this; +}; + +Channel.prototype.prefetch = function(count, global, cb) { + return this.rpc(defs.BasicQos, + Args.prefetch(count, global), + defs.BasicQosOk, cb); +}; + +Channel.prototype.recover = function(cb) { + return this.rpc(defs.BasicRecover, + Args.recover(), + defs.BasicRecoverOk, cb); +}; + +function ConfirmChannel(connection) { + Channel.call(this, connection); +} +inherits(ConfirmChannel, Channel); + +module.exports.ConfirmChannel = ConfirmChannel; + +CallbackModel.prototype.createConfirmChannel = function(cb) { + var ch = new ConfirmChannel(this.connection); + ch.open(function(err) { + if (err !== null) return cb && cb(err); + else { + ch.rpc(defs.ConfirmSelect, {nowait: false}, + defs.ConfirmSelectOk, function(err, _ok) { + if (err !== null) return cb && cb(err); + else cb && cb(null, ch); + }); + } + }); + return ch; +}; + +ConfirmChannel.prototype.publish = function(exchange, routingKey, + content, options, cb) { + this.pushConfirmCallback(cb); + return Channel.prototype.publish.call( + this, exchange, routingKey, content, options); +}; + +ConfirmChannel.prototype.sendToQueue = function(queue, content, + options, cb) { + return this.publish('', queue, content, options, cb); +}; + +ConfirmChannel.prototype.waitForConfirms = function(k) { + var awaiting = []; + var unconfirmed = this.unconfirmed; + unconfirmed.forEach(function(val, index) { + if (val === null); // already confirmed + else { + var confirmed = new Promise(function(resolve, reject) { + unconfirmed[index] = function(err) { + if (val) val(err); + if (err === null) resolve(); + else reject(err); + }; + }); + awaiting.push(confirmed); + } + }); + return Promise.all(awaiting).then(function() { k(); }, + function(err) { k(err); }); +}; diff --git a/node_modules/amqplib/lib/channel.js b/node_modules/amqplib/lib/channel.js new file mode 100644 index 0000000..fc8f17d --- /dev/null +++ b/node_modules/amqplib/lib/channel.js @@ -0,0 +1,498 @@ +// +// +// + +// Channel machinery. + +'use strict'; + +var defs = require('./defs'); +var closeMsg = require('./format').closeMessage; +var inspect = require('./format').inspect; +var methodName = require('./format').methodName; +var assert = require('assert'); +var inherits = require('util').inherits; +var EventEmitter = require('events').EventEmitter; +var fmt = require('util').format; +var IllegalOperationError = require('./error').IllegalOperationError; +var stackCapture = require('./error').stackCapture; +var Buffer = require('safe-buffer').Buffer +function Channel(connection) { + EventEmitter.call( this ); + this.connection = connection; + // for the presently outstanding RPC + this.reply = null; + // for the RPCs awaiting action + this.pending = []; + // for unconfirmed messages + this.lwm = 1; // the least, unconfirmed deliveryTag + this.unconfirmed = []; // rolling window of delivery callbacks + this.on('ack', this.handleConfirm.bind(this, function(cb) { + if (cb) cb(null); + })); + this.on('nack', this.handleConfirm.bind(this, function(cb) { + if (cb) cb(new Error('message nacked')); + })); + this.on('close', function () { + var cb; + while (cb = this.unconfirmed.shift()) { + if (cb) cb(new Error('channel closed')); + } + }) + // message frame state machine + this.handleMessage = acceptDeliveryOrReturn; +} +inherits(Channel, EventEmitter); + +module.exports.Channel = Channel; +module.exports.acceptMessage = acceptMessage; + +var C = Channel.prototype; + +C.allocate = function() { + this.ch = this.connection.freshChannel(this); + return this; +} + +// Incoming frames are either notifications of e.g., message delivery, +// or replies to something we've sent. In general I deal with the +// former by emitting an event, and with the latter by keeping a track +// of what's expecting a reply. +// +// The AMQP specification implies that RPCs can't be pipelined; that +// is, you can have only one outstanding RPC on a channel at a +// time. Certainly that's what RabbitMQ and its clients assume. For +// this reason, I buffer RPCs if the channel is already waiting for a +// reply. + +// Just send the damn frame. +C.sendImmediately = function(method, fields) { + return this.connection.sendMethod(this.ch, method, fields); +}; + +// Invariant: !this.reply -> pending.length == 0. That is, whenever we +// clear a reply, we must send another RPC (and thereby fill +// this.reply) if there is one waiting. The invariant relevant here +// and in `accept`. +C.sendOrEnqueue = function(method, fields, reply) { + if (!this.reply) { // if no reply waiting, we can go + assert(this.pending.length === 0); + this.reply = reply; + this.sendImmediately(method, fields); + } + else { + this.pending.push({method: method, + fields: fields, + reply: reply}); + } +}; + +C.sendMessage = function(fields, properties, content) { + return this.connection.sendMessage( + this.ch, + defs.BasicPublish, fields, + defs.BasicProperties, properties, + content); +}; + +// Internal, synchronously resolved RPC; the return value is resolved +// with the whole frame. +C._rpc = function(method, fields, expect, cb) { + var self = this; + + function reply(err, f) { + if (err === null) { + if (f.id === expect) { + return cb(null, f); + } + else { + // We have detected a problem, so it's up to us to close the + // channel + var expectedName = methodName(expect); + + var e = new Error(fmt("Expected %s; got %s", + expectedName, inspect(f, false))); + self.closeWithError(f.id, fmt('Expected %s; got %s', + expectedName, methodName(f.id)), + defs.constants.UNEXPECTED_FRAME, e); + return cb(e); + } + } + // An error will be given if, for example, this is waiting to be + // sent and the connection closes + else if (err instanceof Error) return cb(err); + // A close frame will be given if this is the RPC awaiting reply + // and the channel is closed by the server + else { + // otherwise, it's a close frame + var closeReason = + (err.fields.classId << 16) + err.fields.methodId; + var e = (method === closeReason) + ? fmt("Operation failed: %s; %s", + methodName(method), closeMsg(err)) + : fmt("Channel closed by server: %s", closeMsg(err)); + var closeFrameError = new Error(e); + closeFrameError.code = err.fields.replyCode; + closeFrameError.classId = err.fields.classId; + closeFrameError.methodId = err.fields.methodId; + return cb(closeFrameError); + } + } + + this.sendOrEnqueue(method, fields, reply); +}; + +// Shutdown protocol. There's three scenarios: +// +// 1. The application decides to shut the channel +// 2. The server decides to shut the channel, possibly because of +// something the application did +// 3. The connection is closing, so there won't be any more frames +// going back and forth. +// +// 1 and 2 involve an exchange of method frames (Close and CloseOk), +// while 3 doesn't; the connection simply says "shutdown" to the +// channel, which then acts as if it's closing, without going through +// the exchange. + +function invalidOp(msg, stack) { + return function() { + throw new IllegalOperationError(msg, stack); + }; +} + +function invalidateSend(ch, msg, stack) { + ch.sendImmediately = ch.sendOrEnqueue = ch.sendMessage = + invalidOp(msg, stack); +} + +// Move to entirely closed state. +C.toClosed = function(capturedStack) { + this._rejectPending(); + invalidateSend(this, 'Channel closed', capturedStack); + this.accept = invalidOp('Channel closed', capturedStack); + this.connection.releaseChannel(this.ch); + this.emit('close'); +}; + +// Stop being able to send and receive methods and content. Used when +// we close the channel. Invokes the continuation once the server has +// acknowledged the close, but before the channel is moved to the +// closed state. +C.toClosing = function(capturedStack, k) { + var send = this.sendImmediately.bind(this); + invalidateSend(this, 'Channel closing', capturedStack); + + this.accept = function(f) { + if (f.id === defs.ChannelCloseOk) { + if (k) k(); + var s = stackCapture('ChannelCloseOk frame received'); + this.toClosed(s); + } + else if (f.id === defs.ChannelClose) { + send(defs.ChannelCloseOk, {}); + } + // else ignore frame + }; +}; + +C._rejectPending = function() { + function rej(r) { + r(new Error("Channel ended, no reply will be forthcoming")); + } + if (this.reply !== null) rej(this.reply); + this.reply = null; + + var discard; + while (discard = this.pending.shift()) rej(discard.reply); + this.pending = null; // so pushes will break +}; + +C.closeBecause = function(reason, code, k) { + this.sendImmediately(defs.ChannelClose, { + replyText: reason, + replyCode: code, + methodId:0, classId: 0 + }); + var s = stackCapture('closeBecause called: ' + reason); + this.toClosing(s, k); +}; + +// If we close because there's been an error, we need to distinguish +// between what we tell the server (`reason`) and what we report as +// the cause in the client (`error`). +C.closeWithError = function(id, reason, code, error) { + var self = this; + this.closeBecause(reason, code, function() { + error.code = code; + // content frames and consumer errors do not provide a method a class/method ID + if (id) { + error.classId = defs.info(id).classId; + error.methodId = defs.info(id).methodId; + } + self.emit('error', error); + }); +}; + +// A trampolining state machine for message frames on a channel. A +// message arrives in at least two frames: first, a method announcing +// the message (either a BasicDeliver or BasicGetOk); then, a message +// header with the message properties; then, zero or more content +// frames. + +// Keep the try/catch localised, in an attempt to avoid disabling +// optimisation +C.acceptMessageFrame = function(f) { + try { + this.handleMessage = this.handleMessage(f); + } + catch (msg) { + if (typeof msg === 'string') { + this.closeWithError(f.id, msg, defs.constants.UNEXPECTED_FRAME, + new Error(msg)); + } + else if (msg instanceof Error) { + this.closeWithError(f.id, 'Error while processing message', + defs.constants.INTERNAL_ERROR, msg); + } + else { + this.closeWithError(f.id, 'Internal error while processing message', + defs.constants.INTERNAL_ERROR, + new Error(msg.toString())); + } + } +}; + +// Kick off a message delivery given a BasicDeliver or BasicReturn +// frame (BasicGet uses the RPC mechanism) +function acceptDeliveryOrReturn(f) { + var event; + if (f.id === defs.BasicDeliver) event = 'delivery'; + else if (f.id === defs.BasicReturn) event = 'return'; + else throw fmt("Expected BasicDeliver or BasicReturn; got %s", + inspect(f)); + + var self = this; + var fields = f.fields; + return acceptMessage(function(message) { + message.fields = fields; + self.emit(event, message); + }); +} + +// Move to the state of waiting for message frames (headers, then +// one or more content frames) +function acceptMessage(continuation) { + var totalSize = 0, remaining = 0; + var buffers = null; + + var message = { + fields: null, + properties: null, + content: null + }; + + return headers; + + // expect a headers frame + function headers(f) { + if (f.id === defs.BasicProperties) { + message.properties = f.fields; + totalSize = remaining = f.size; + + // for zero-length messages, content frames aren't required. + if (totalSize === 0) { + message.content = Buffer.alloc(0); + continuation(message); + return acceptDeliveryOrReturn; + } + else { + return content; + } + } + else { + throw "Expected headers frame after delivery"; + } + } + + // expect a content frame + // %%% TODO cancelled messages (sent as zero-length content frame) + function content(f) { + if (f.content) { + var size = f.content.length; + remaining -= size; + if (remaining === 0) { + if (buffers !== null) { + buffers.push(f.content); + message.content = Buffer.concat(buffers); + } + else { + message.content = f.content; + } + continuation(message); + return acceptDeliveryOrReturn; + } + else if (remaining < 0) { + throw fmt("Too much content sent! Expected %d bytes", + totalSize); + } + else { + if (buffers !== null) + buffers.push(f.content); + else + buffers = [f.content]; + return content; + } + } + else throw "Expected content frame after headers" + } +} + +C.handleConfirm = function(handle, f) { + var tag = f.deliveryTag; + var multi = f.multiple; + + if (multi) { + var confirmed = this.unconfirmed.splice(0, tag - this.lwm + 1); + this.lwm = tag + 1; + confirmed.forEach(handle); + } + else { + var c; + if (tag === this.lwm) { + c = this.unconfirmed.shift(); + this.lwm++; + // Advance the LWM and the window to the next non-gap, or + // possibly to the end + while (this.unconfirmed[0] === null) { + this.unconfirmed.shift(); + this.lwm++; + } + } + else { + c = this.unconfirmed[tag - this.lwm]; + this.unconfirmed[tag - this.lwm] = null; + } + // Technically, in the single-deliveryTag case, I should report a + // protocol breach if it's already been confirmed. + handle(c); + } +}; + +C.pushConfirmCallback = function(cb) { + // `null` is used specifically for marking already confirmed slots, + // so I coerce `undefined` and `null` to false; functions are never + // falsey. + this.unconfirmed.push(cb || false); +}; + +// Interface for connection to use + +C.accept = function(f) { + + switch (f.id) { + + // Message frames + case undefined: // content frame! + case defs.BasicDeliver: + case defs.BasicReturn: + case defs.BasicProperties: + return this.acceptMessageFrame(f); + + // confirmations, need to do confirm.select first + case defs.BasicAck: + return this.emit('ack', f.fields); + case defs.BasicNack: + return this.emit('nack', f.fields); + case defs.BasicCancel: + // The broker can send this if e.g., the queue is deleted. + return this.emit('cancel', f.fields); + + case defs.ChannelClose: + // Any remote closure is an error to us. Reject the pending reply + // with the close frame, so it can see whether it was that + // operation that caused it to close. + if (this.reply) { + var reply = this.reply; this.reply = null; + reply(f); + } + var emsg = "Channel closed by server: " + closeMsg(f); + this.sendImmediately(defs.ChannelCloseOk, {}); + + var error = new Error(emsg); + error.code = f.fields.replyCode; + error.classId = f.fields.classId; + error.methodId = f.fields.methodId; + this.emit('error', error); + + var s = stackCapture(emsg); + this.toClosed(s); + return; + + case defs.BasicFlow: + // RabbitMQ doesn't send this, it just blocks the TCP socket + return this.closeWithError(f.id, "Flow not implemented", + defs.constants.NOT_IMPLEMENTED, + new Error('Flow not implemented')); + + default: // assume all other things are replies + // Resolving the reply may lead to another RPC; to make sure we + // don't hold that up, clear this.reply + var reply = this.reply; this.reply = null; + // however, maybe there's an RPC waiting to go? If so, that'll + // fill this.reply again, restoring the invariant. This does rely + // on any response being recv'ed after resolving the promise, + // below; hence, I use synchronous defer. + if (this.pending.length > 0) { + var send = this.pending.shift(); + this.reply = send.reply; + this.sendImmediately(send.method, send.fields); + } + return reply(null, f); + } +}; + +C.onBufferDrain = function() { + this.emit('drain'); +}; + + +// This adds just a bit more stuff useful for the APIs, but not +// low-level machinery. +function BaseChannel(connection) { + Channel.call(this, connection); + this.consumers = {}; +} +inherits(BaseChannel, Channel); + +module.exports.BaseChannel = BaseChannel; + +// Not sure I like the ff, it's going to be changing hidden classes +// all over the place. On the other hand, whaddya do. +BaseChannel.prototype.registerConsumer = function(tag, callback) { + this.consumers[tag] = callback; +}; + +BaseChannel.prototype.unregisterConsumer = function(tag) { + delete this.consumers[tag]; +}; + +BaseChannel.prototype.dispatchMessage = function(fields, message) { + var consumerTag = fields.consumerTag; + var consumer = this.consumers[consumerTag]; + if (consumer) { + return consumer(message); + } + else { + // %%% Surely a race here + throw new Error("Unknown consumer: " + consumerTag); + } +}; + +BaseChannel.prototype.handleDelivery = function(message) { + return this.dispatchMessage(message.fields, message); +}; + +BaseChannel.prototype.handleCancel = function(fields) { + return this.dispatchMessage(fields, null); +}; diff --git a/node_modules/amqplib/lib/channel_model.js b/node_modules/amqplib/lib/channel_model.js new file mode 100644 index 0000000..2097fd1 --- /dev/null +++ b/node_modules/amqplib/lib/channel_model.js @@ -0,0 +1,318 @@ +// +// +// + +'use strict'; + +var defs = require('./defs'); +var Promise = require('bluebird'); +var inherits = require('util').inherits; +var EventEmitter = require('events').EventEmitter; +var BaseChannel = require('./channel').BaseChannel; +var acceptMessage = require('./channel').acceptMessage; +var Args = require('./api_args'); + +function ChannelModel(connection) { + if (!(this instanceof ChannelModel)) + return new ChannelModel(connection); + EventEmitter.call( this ); + this.connection = connection; + var self = this; + ['error', 'close', 'blocked', 'unblocked'].forEach(function(ev) { + connection.on(ev, self.emit.bind(self, ev)); + }); +} +inherits(ChannelModel, EventEmitter); + +module.exports.ChannelModel = ChannelModel; + +var CM = ChannelModel.prototype; + +CM.close = function() { + return Promise.fromCallback(this.connection.close.bind(this.connection)); +}; + +// Channels + +function Channel(connection) { + BaseChannel.call(this, connection); + this.on('delivery', this.handleDelivery.bind(this)); + this.on('cancel', this.handleCancel.bind(this)); +} +inherits(Channel, BaseChannel); + +module.exports.Channel = Channel; + +CM.createChannel = function() { + var c = new Channel(this.connection); + return c.open().then(function(openOk) { return c; }); +}; + +var C = Channel.prototype; + +// An RPC that returns a 'proper' promise, which resolves to just the +// response's fields; this is intended to be suitable for implementing +// API procedures. +C.rpc = function(method, fields, expect) { + var self = this; + return Promise.fromCallback(function(cb) { + return self._rpc(method, fields, expect, cb); + }) + .then(function(f) { + return f.fields; + }); +}; + +// Do the remarkably simple channel open handshake +C.open = function() { + return Promise.try(this.allocate.bind(this)).then( + function(ch) { + return ch.rpc(defs.ChannelOpen, {outOfBand: ""}, + defs.ChannelOpenOk); + }); +}; + +C.close = function() { + var self = this; + return Promise.fromCallback(function(cb) { + return self.closeBecause("Goodbye", defs.constants.REPLY_SUCCESS, + cb); + }); +}; + +// === Public API, declaring queues and stuff === + +C.assertQueue = function(queue, options) { + return this.rpc(defs.QueueDeclare, + Args.assertQueue(queue, options), + defs.QueueDeclareOk); +}; + +C.checkQueue = function(queue) { + return this.rpc(defs.QueueDeclare, + Args.checkQueue(queue), + defs.QueueDeclareOk); +}; + +C.deleteQueue = function(queue, options) { + return this.rpc(defs.QueueDelete, + Args.deleteQueue(queue, options), + defs.QueueDeleteOk); +}; + +C.purgeQueue = function(queue) { + return this.rpc(defs.QueuePurge, + Args.purgeQueue(queue), + defs.QueuePurgeOk); +}; + +C.bindQueue = function(queue, source, pattern, argt) { + return this.rpc(defs.QueueBind, + Args.bindQueue(queue, source, pattern, argt), + defs.QueueBindOk); +}; + +C.unbindQueue = function(queue, source, pattern, argt) { + return this.rpc(defs.QueueUnbind, + Args.unbindQueue(queue, source, pattern, argt), + defs.QueueUnbindOk); +}; + +C.assertExchange = function(exchange, type, options) { + // The server reply is an empty set of fields, but it's convenient + // to have the exchange name handed to the continuation. + return this.rpc(defs.ExchangeDeclare, + Args.assertExchange(exchange, type, options), + defs.ExchangeDeclareOk) + .then(function(_ok) { return { exchange: exchange }; }); +}; + +C.checkExchange = function(exchange) { + return this.rpc(defs.ExchangeDeclare, + Args.checkExchange(exchange), + defs.ExchangeDeclareOk); +}; + +C.deleteExchange = function(name, options) { + return this.rpc(defs.ExchangeDelete, + Args.deleteExchange(name, options), + defs.ExchangeDeleteOk); +}; + +C.bindExchange = function(dest, source, pattern, argt) { + return this.rpc(defs.ExchangeBind, + Args.bindExchange(dest, source, pattern, argt), + defs.ExchangeBindOk); +}; + +C.unbindExchange = function(dest, source, pattern, argt) { + return this.rpc(defs.ExchangeUnbind, + Args.unbindExchange(dest, source, pattern, argt), + defs.ExchangeUnbindOk); +}; + +// Working with messages + +C.publish = function(exchange, routingKey, content, options) { + var fieldsAndProps = Args.publish(exchange, routingKey, options); + return this.sendMessage(fieldsAndProps, fieldsAndProps, content); +}; + +C.sendToQueue = function(queue, content, options) { + return this.publish('', queue, content, options); +}; + +C.consume = function(queue, callback, options) { + var self = this; + // NB we want the callback to be run synchronously, so that we've + // registered the consumerTag before any messages can arrive. + var fields = Args.consume(queue, options); + return Promise.fromCallback(function(cb) { + self._rpc(defs.BasicConsume, fields, defs.BasicConsumeOk, cb); + }) + .then(function(ok) { + self.registerConsumer(ok.fields.consumerTag, callback); + return ok.fields; + }); +}; + +C.cancel = function(consumerTag) { + var self = this; + return Promise.fromCallback(function(cb) { + self._rpc(defs.BasicCancel, Args.cancel(consumerTag), + defs.BasicCancelOk, + cb); + }) + .then(function(ok) { + self.unregisterConsumer(consumerTag); + return ok.fields; + }); +}; + +C.get = function(queue, options) { + var self = this; + var fields = Args.get(queue, options); + return Promise.fromCallback(function(cb) { + return self.sendOrEnqueue(defs.BasicGet, fields, cb); + }) + .then(function(f) { + if (f.id === defs.BasicGetEmpty) { + return false; + } + else if (f.id === defs.BasicGetOk) { + var fields = f.fields; + return new Promise(function(resolve) { + self.handleMessage = acceptMessage(function(m) { + m.fields = fields; + resolve(m); + }); + }); + } + else { + throw new Error("Unexpected response to BasicGet: " + + inspect(f)); + } + }) +}; + +C.ack = function(message, allUpTo) { + this.sendImmediately( + defs.BasicAck, + Args.ack(message.fields.deliveryTag, allUpTo)); +}; + +C.ackAll = function() { + this.sendImmediately(defs.BasicAck, Args.ack(0, true)); +}; + +C.nack = function(message, allUpTo, requeue) { + this.sendImmediately( + defs.BasicNack, + Args.nack(message.fields.deliveryTag, allUpTo, requeue)); +}; + +C.nackAll = function(requeue) { + this.sendImmediately(defs.BasicNack, + Args.nack(0, true, requeue)); +}; + +// `Basic.Nack` is not available in older RabbitMQ versions (or in the +// AMQP specification), so you have to use the one-at-a-time +// `Basic.Reject`. This is otherwise synonymous with +// `#nack(message, false, requeue)`. +C.reject = function(message, requeue) { + this.sendImmediately( + defs.BasicReject, + Args.reject(message.fields.deliveryTag, requeue)); +}; + +// There are more options in AMQP than exposed here; RabbitMQ only +// implements prefetch based on message count, and only for individual +// channels or consumers. RabbitMQ v3.3.0 and after treat prefetch +// (without `global` set) as per-consumer (for consumers following), +// and prefetch with `global` set as per-channel. +C.prefetch = C.qos = function(count, global) { + return this.rpc(defs.BasicQos, + Args.prefetch(count, global), + defs.BasicQosOk); +}; + +C.recover = function() { + return this.rpc(defs.BasicRecover, + Args.recover(), + defs.BasicRecoverOk); +}; + +// Confirm channel. This is a channel with confirms 'switched on', +// meaning sent messages will provoke a responding 'ack' or 'nack' +// from the server. The upshot of this is that `publish` and +// `sendToQueue` both take a callback, which will be called either +// with `null` as its argument to signify 'ack', or an exception as +// its argument to signify 'nack'. + +function ConfirmChannel(connection) { + Channel.call(this, connection); +} +inherits(ConfirmChannel, Channel); + +module.exports.ConfirmChannel = ConfirmChannel; + +CM.createConfirmChannel = function() { + var c = new ConfirmChannel(this.connection); + return c.open() + .then(function(openOk) { + return c.rpc(defs.ConfirmSelect, {nowait: false}, + defs.ConfirmSelectOk) + }) + .then(function() { return c; }); +}; + +var CC = ConfirmChannel.prototype; + +CC.publish = function(exchange, routingKey, content, options, cb) { + this.pushConfirmCallback(cb); + return C.publish.call(this, exchange, routingKey, content, options); +}; + +CC.sendToQueue = function(queue, content, options, cb) { + return this.publish('', queue, content, options, cb); +}; + +CC.waitForConfirms = function() { + var awaiting = []; + var unconfirmed = this.unconfirmed; + unconfirmed.forEach(function(val, index) { + if (val === null); // already confirmed + else { + var confirmed = new Promise(function(resolve, reject) { + unconfirmed[index] = function(err) { + if (val) val(err); + if (err === null) resolve(); + else reject(err); + }; + }); + awaiting.push(confirmed); + } + }); + return Promise.all(awaiting); +}; diff --git a/node_modules/amqplib/lib/codec.js b/node_modules/amqplib/lib/codec.js new file mode 100644 index 0000000..c4bc5b0 --- /dev/null +++ b/node_modules/amqplib/lib/codec.js @@ -0,0 +1,321 @@ +// +// +// + +/* + +The AMQP 0-9-1 is a mess when it comes to the types that can be +encoded on the wire. + +There are four encoding schemes, and three overlapping sets of types: +frames, methods, (field-)tables, and properties. + +Each *frame type* has a set layout in which values of given types are +concatenated along with sections of "raw binary" data. + +In frames there are `shortstr`s, that is length-prefixed strings of +UTF8 chars, 8 bit unsigned integers (called `octet`), unsigned 16 bit +integers (called `short` or `short-uint`), unsigned 32 bit integers +(called `long` or `long-uint`), unsigned 64 bit integers (called +`longlong` or `longlong-uint`), and flags (called `bit`). + +Methods are encoded as a frame giving a method ID and a sequence of +arguments of known types. The encoded method argument values are +concatenated (with some fun complications around "packing" consecutive +bit values into bytes). + +Along with the types given in frames, method arguments may be long +byte strings (`longstr`, not required to be UTF8) or 64 bit unsigned +integers to be interpreted as timestamps (yeah I don't know why +either), or arbitrary sets of key-value pairs (called `field-table`). + +Inside a field table the keys are `shortstr` and the values are +prefixed with a byte tag giving the type. The types are any of the +above except for bits (which are replaced by byte-wide `bool`), along +with a NULL value `void`, a special fixed-precision number encoding +(`decimal`), IEEE754 `float`s and `double`s, signed integers, +`field-array` (a sequence of tagged values), and nested field-tables. + +RabbitMQ and QPid use a subset of the field-table types, and different +value tags, established before the AMQP 0-9-1 specification was +published. So far as I know, no-one uses the types and tags as +published. http://www.rabbitmq.com/amqp-0-9-1-errata.html gives the +list of field-table types. + +Lastly, there are (sets of) properties, only one of which is given in +AMQP 0-9-1: `BasicProperties`. These are almost the same as methods, +except that they appear in content header frames, which include a +content size, and they carry a set of flags indicating which +properties are present. This scheme can save ones of bytes per message +(messages which take a minimum of three frames each to send). + +*/ + +'use strict'; + +var ints = require('buffer-more-ints'); + +// JavaScript uses only doubles so what I'm testing for is whether +// it's *better* to encode a number as a float or double. This really +// just amounts to testing whether there's a fractional part to the +// number, except that see below. NB I don't use bitwise operations to +// do this 'efficiently' -- it would mask the number to 32 bits. +// +// At 2^50, doubles don't have sufficient precision to distinguish +// between floating point and integer numbers (`Math.pow(2, 50) + 0.1 +// === Math.pow(2, 50)` (and, above 2^53, doubles cannot represent all +// integers (`Math.pow(2, 53) + 1 === Math.pow(2, 53)`)). Hence +// anything with a magnitude at or above 2^50 may as well be encoded +// as a 64-bit integer. Except that only signed integers are supported +// by RabbitMQ, so anything above 2^63 - 1 must be a double. +function isFloatingPoint(n) { + return n >= 0x8000000000000000 || + (Math.abs(n) < 0x4000000000000 + && Math.floor(n) !== n); +} + +function encodeTable(buffer, val, offset) { + var start = offset; + offset += 4; // leave room for the table length + for (var key in val) { + if (val[key] !== undefined) { + var len = Buffer.byteLength(key); + buffer.writeUInt8(len, offset); offset++; + buffer.write(key, offset, 'utf8'); offset += len; + offset += encodeFieldValue(buffer, val[key], offset); + } + } + var size = offset - start; + buffer.writeUInt32BE(size - 4, start); + return size; +} + +function encodeArray(buffer, val, offset) { + var start = offset; + offset += 4; + for (var i=0, num=val.length; i < num; i++) { + offset += encodeFieldValue(buffer, val[i], offset); + } + var size = offset - start; + buffer.writeUInt32BE(size - 4, start); + return size; +} + +function encodeFieldValue(buffer, value, offset) { + var start = offset; + var type = typeof value, val = value; + // A trapdoor for specifying a type, e.g., timestamp + if (value && type === 'object' && value.hasOwnProperty('!')) { + val = value.value; + type = value['!']; + } + + // If it's a JS number, we'll have to guess what type to encode it + // as. + if (type == 'number') { + // Making assumptions about the kind of number (floating point + // v integer, signed, unsigned, size) desired is dangerous in + // general; however, in practice RabbitMQ uses only + // longstrings and unsigned integers in its arguments, and + // other clients generally conflate number types anyway. So + // the only distinction we care about is floating point vs + // integers, preferring integers since those can be promoted + // if necessary. If floating point is required, we may as well + // use double precision. + if (isFloatingPoint(val)) { + type = 'double'; + } + else { // only signed values are used in tables by + // RabbitMQ. It *used* to (< v3.3.0) treat the byte 'b' + // type as unsigned, but most clients (and the spec) + // think it's signed, and now RabbitMQ does too. + if (val < 128 && val >= -128) { + type = 'byte'; + } + else if (val >= -0x8000 && val < 0x8000) { + type = 'short' + } + else if (val >= -0x80000000 && val < 0x80000000) { + type = 'int'; + } + else { + type = 'long'; + } + } + } + + function tag(t) { buffer.write(t, offset); offset++; } + + switch (type) { + case 'string': // no shortstr in field tables + var len = Buffer.byteLength(val, 'utf8'); + tag('S'); + buffer.writeUInt32BE(len, offset); offset += 4; + buffer.write(val, offset, 'utf8'); offset += len; + break; + case 'object': + if (val === null) { + tag('V'); + } + else if (Array.isArray(val)) { + tag('A'); + offset += encodeArray(buffer, val, offset); + } + else if (Buffer.isBuffer(val)) { + tag('x'); + buffer.writeUInt32BE(val.length, offset); offset += 4; + val.copy(buffer, offset); offset += val.length; + } + else { + tag('F'); + offset += encodeTable(buffer, val, offset); + } + break; + case 'boolean': + tag('t'); + buffer.writeUInt8((val) ? 1 : 0, offset); offset++; + break; + // These are the types that are either guessed above, or + // explicitly given using the {'!': type} notation. + case 'double': + case 'float64': + tag('d'); + buffer.writeDoubleBE(val, offset); + offset += 8; + break; + case 'byte': + case 'int8': + tag('b'); + buffer.writeInt8(val, offset); offset++; + break; + case 'short': + case 'int16': + tag('s'); + buffer.writeInt16BE(val, offset); offset += 2; + break; + case 'int': + case 'int32': + tag('I'); + buffer.writeInt32BE(val, offset); offset += 4; + break; + case 'long': + case 'int64': + tag('l'); + ints.writeInt64BE(buffer, val, offset); offset += 8; + break; + + // Now for exotic types, those can _only_ be denoted by using + // `{'!': type, value: val} + case 'timestamp': + tag('T'); + ints.writeUInt64BE(buffer, val, offset); offset += 8; + break; + case 'float': + tag('f'); + buffer.writeFloatBE(val, offset); offset += 4; + break; + case 'decimal': + tag('D'); + if (val.hasOwnProperty('places') && val.hasOwnProperty('digits') + && val.places >= 0 && val.places < 256) { + buffer[offset] = val.places; offset++; + buffer.writeUInt32BE(val.digits, offset); offset += 4; + } + else throw new TypeError( + "Decimal value must be {'places': 0..255, 'digits': uint32}, " + + "got " + JSON.stringify(val)); + break; + default: + throw new TypeError('Unknown type to encode: ' + type); + } + return offset - start; +} + +// Assume we're given a slice of the buffer that contains just the +// fields. +function decodeFields(slice) { + var fields = {}, offset = 0, size = slice.length; + var len, key, val; + + function decodeFieldValue() { + var tag = String.fromCharCode(slice[offset]); offset++; + switch (tag) { + case 'b': + val = slice.readInt8(offset); offset++; + break; + case 'S': + len = slice.readUInt32BE(offset); offset += 4; + val = slice.toString('utf8', offset, offset + len); + offset += len; + break; + case 'I': + val = slice.readInt32BE(offset); offset += 4; + break; + case 'D': // only positive decimals, apparently. + var places = slice[offset]; offset++; + var digits = slice.readUInt32BE(offset); offset += 4; + val = {'!': 'decimal', value: {places: places, digits: digits}}; + break; + case 'T': + val = ints.readUInt64BE(slice, offset); offset += 8; + val = {'!': 'timestamp', value: val}; + break; + case 'F': + len = slice.readUInt32BE(offset); offset += 4; + val = decodeFields(slice.slice(offset, offset + len)); + offset += len; + break; + case 'A': + len = slice.readUInt32BE(offset); offset += 4; + decodeArray(offset + len); + // NB decodeArray will itself update offset and val + break; + case 'd': + val = slice.readDoubleBE(offset); offset += 8; + break; + case 'f': + val = slice.readFloatBE(offset); offset += 4; + break; + case 'l': + val = ints.readInt64BE(slice, offset); offset += 8; + break; + case 's': + val = slice.readInt16BE(offset); offset += 2; + break; + case 't': + val = slice[offset] != 0; offset++; + break; + case 'V': + val = null; + break; + case 'x': + len = slice.readUInt32BE(offset); offset += 4; + val = slice.slice(offset, offset + len); + offset += len; + break; + default: + throw new TypeError('Unexpected type tag "' + tag +'"'); + } + } + + function decodeArray(until) { + var vals = []; + while (offset < until) { + decodeFieldValue(); + vals.push(val); + } + val = vals; + } + + while (offset < size) { + len = slice.readUInt8(offset); offset++; + key = slice.toString('utf8', offset, offset + len); + offset += len; + decodeFieldValue(); + fields[key] = val; + } + return fields; +} + +module.exports.encodeTable = encodeTable; +module.exports.decodeFields = decodeFields; diff --git a/node_modules/amqplib/lib/connect.js b/node_modules/amqplib/lib/connect.js new file mode 100644 index 0000000..27a042e --- /dev/null +++ b/node_modules/amqplib/lib/connect.js @@ -0,0 +1,185 @@ +// +// +// + +// General-purpose API for glueing everything together. + +'use strict'; + +var URL = require('url-parse'); +var QS = require('querystring'); +var Connection = require('./connection').Connection; +var fmt = require('util').format; +var credentials = require('./credentials'); + +function copyInto(obj, target) { + var keys = Object.keys(obj); + var i = keys.length; + while (i--) { + var k = keys[i]; + target[k] = obj[k]; + } + return target; +} + +// Adapted from util._extend, which is too fringe to use. +function clone(obj) { + return copyInto(obj, {}); +} + +var CLIENT_PROPERTIES = { + "product": "amqplib", + "version": require('../package.json').version, + "platform": fmt('Node.JS %s', process.version), + "information": "http://squaremo.github.io/amqp.node", + "capabilities": { + "publisher_confirms": true, + "exchange_exchange_bindings": true, + "basic.nack": true, + "consumer_cancel_notify": true, + "connection.blocked": true, + "authentication_failure_close": true + } +}; + +// Construct the main frames used in the opening handshake +function openFrames(vhost, query, credentials, extraClientProperties) { + if (!vhost) + vhost = '/'; + else + vhost = QS.unescape(vhost); + + var query = query || {}; + + function intOrDefault(val, def) { + return (val === undefined) ? def : parseInt(val); + } + + var clientProperties = Object.create(CLIENT_PROPERTIES); + + return { + // start-ok + 'clientProperties': copyInto(extraClientProperties, clientProperties), + 'mechanism': credentials.mechanism, + 'response': credentials.response(), + 'locale': query.locale || 'en_US', + + // tune-ok + 'channelMax': intOrDefault(query.channelMax, 0), + 'frameMax': intOrDefault(query.frameMax, 0x1000), + 'heartbeat': intOrDefault(query.heartbeat, 0), + + // open + 'virtualHost': vhost, + 'capabilities': '', + 'insist': 0 + }; +} + +// Decide on credentials based on what we're supplied. +function credentialsFromUrl(parts) { + var user = 'guest', passwd = 'guest'; + if (parts.username != '' || parts.password != '') { + user = (parts.username) ? unescape(parts.username) : ''; + passwd = (parts.password) ? unescape(parts.password) : ''; + } + return credentials.plain(user, passwd); +} + +function connect(url, socketOptions, openCallback) { + // tls.connect uses `util._extend()` on the options given it, which + // copies only properties mentioned in `Object.keys()`, when + // processing the options. So I have to make copies too, rather + // than using `Object.create()`. + var sockopts = clone(socketOptions || {}); + url = url || 'amqp://localhost'; + + var noDelay = !!sockopts.noDelay; + var timeout = sockopts.timeout; + var keepAlive = !!sockopts.keepAlive; + // 0 is default for node + var keepAliveDelay = sockopts.keepAliveDelay || 0; + + var extraClientProperties = sockopts.clientProperties || {}; + + var protocol, fields; + if (typeof url === 'object') { + protocol = (url.protocol || 'amqp') + ':'; + sockopts.host = url.hostname; + sockopts.servername = url.hostname; + sockopts.port = url.port || ((protocol === 'amqp:') ? 5672 : 5671); + + var user, pass; + // Only default if both are missing, to have the same behaviour as + // the stringly URL. + if (url.username == undefined && url.password == undefined) { + user = 'guest'; pass = 'guest'; + } else { + user = url.username || ''; + pass = url.password || ''; + } + + var config = { + locale: url.locale, + channelMax: url.channelMax, + frameMax: url.frameMax, + heartbeat: url.heartbeat, + }; + + fields = openFrames(url.vhost, config, sockopts.credentials || credentials.plain(user, pass), extraClientProperties); + } else { + var parts = URL(url, true); // yes, parse the query string + protocol = parts.protocol; + sockopts.host = parts.hostname; + sockopts.servername = parts.hostname; + sockopts.port = parseInt(parts.port) || ((protocol === 'amqp:') ? 5672 : 5671); + var vhost = parts.pathname ? parts.pathname.substr(1) : null; + fields = openFrames(vhost, parts.query, sockopts.credentials || credentialsFromUrl(parts), extraClientProperties); + } + + var sockok = false; + var sock; + + function onConnect() { + sockok = true; + sock.setNoDelay(noDelay); + if (keepAlive) sock.setKeepAlive(keepAlive, keepAliveDelay); + + var c = new Connection(sock); + c.open(fields, function(err, ok) { + // disable timeout once the connection is open, we don't want + // it fouling things + if (timeout) sock.setTimeout(0); + if (err === null) { + openCallback(null, c); + } + else openCallback(err); + }); + } + + if (protocol === 'amqp:') { + sock = require('net').connect(sockopts, onConnect); + } + else if (protocol === 'amqps:') { + sock = require('tls').connect(sockopts, onConnect); + } + else { + throw new Error("Expected amqp: or amqps: as the protocol; got " + protocol); + } + + if (timeout) { + sock.setTimeout(timeout, function() { + sock.end(); + sock.destroy(); + openCallback(new Error('connect ETIMEDOUT')); + }); + } + + sock.once('error', function(err) { + if (!sockok) openCallback(err); + }); + +} + +module.exports.connect = connect; +module.exports.credentialsFromUrl = credentialsFromUrl; diff --git a/node_modules/amqplib/lib/connection.js b/node_modules/amqplib/lib/connection.js new file mode 100644 index 0000000..f65138c --- /dev/null +++ b/node_modules/amqplib/lib/connection.js @@ -0,0 +1,647 @@ +// +// +// + +'use strict'; + +var defs = require('./defs'); +var constants = defs.constants; +var frame = require('./frame'); +var HEARTBEAT = frame.HEARTBEAT; +var Mux = require('./mux').Mux; +var Buffer = require('safe-buffer').Buffer + +var Duplex = + require('stream').Duplex || + require('readable-stream/duplex'); +var EventEmitter = require('events').EventEmitter; +var Heart = require('./heartbeat').Heart; + +var methodName = require('./format').methodName; +var closeMsg = require('./format').closeMessage; +var inspect = require('./format').inspect; + +var BitSet = require('./bitset').BitSet; +var inherits = require('util').inherits; +var fmt = require('util').format; +var PassThrough = require('stream').PassThrough || + require('readable-stream/passthrough'); +var IllegalOperationError = require('./error').IllegalOperationError; +var stackCapture = require('./error').stackCapture; + +// High-water mark for channel write buffers, in 'objects' (which are +// encoded frames as buffers). +var DEFAULT_WRITE_HWM = 1024; +// If all the frames of a message (method, properties, content) total +// to less than this, copy them into a single buffer and write it all +// at once. Note that this is less than the minimum frame size: if it +// was greater, we might have to fragment the content. +var SINGLE_CHUNK_THRESHOLD = 2048; + +function Connection(underlying) { + EventEmitter.call( this ); + var stream = this.stream = wrapStream(underlying); + this.muxer = new Mux(stream); + + // frames + this.rest = Buffer.alloc(0); + this.frameMax = constants.FRAME_MIN_SIZE; + this.sentSinceLastCheck = false; + this.recvSinceLastCheck = false; + + this.expectSocketClose = false; + this.freeChannels = new BitSet(); + this.channels = [{channel: {accept: channel0(this)}, + buffer: underlying}]; +} +inherits(Connection, EventEmitter); + +var C = Connection.prototype; + +// Usual frame accept mode +function mainAccept(frame) { + var rec = this.channels[frame.channel]; + if (rec) { return rec.channel.accept(frame); } + // NB CHANNEL_ERROR may not be right, but I don't know what is .. + else + this.closeWithError( + fmt('Frame on unknown channel %d', frame.channel), + constants.CHANNEL_ERROR, + new Error(fmt("Frame on unknown channel: %s", + inspect(frame, false)))); +} + +// Handle anything that comes through on channel 0, that's the +// connection control channel. This is only used once mainAccept is +// installed as the frame handler, after the opening handshake. +function channel0(connection) { + return function(f) { + // Once we get a 'close', we know 1. we'll get no more frames, and + // 2. anything we send except close, or close-ok, will be + // ignored. If we already sent 'close', this won't be invoked since + // we're already in closing mode; if we didn't well we're not going + // to send it now are we. + if (f === HEARTBEAT); // ignore; it's already counted as activity + // on the socket, which is its purpose + else if (f.id === defs.ConnectionClose) { + // Oh. OK. I guess we're done here then. + connection.sendMethod(0, defs.ConnectionCloseOk, {}); + var emsg = fmt('Connection closed: %s', closeMsg(f)); + var s = stackCapture(emsg); + var e = new Error(emsg); + e.code = f.fields.replyCode; + if (isFatalError(e)) { + connection.emit('error', e); + } + connection.toClosed(s, e); + } + else if (f.id === defs.ConnectionBlocked) { + connection.emit('blocked', f.fields.reason); + } + else if (f.id === defs.ConnectionUnblocked) { + connection.emit('unblocked'); + } + else { + connection.closeWithError( + fmt("Unexpected frame on channel 0"), + constants.UNEXPECTED_FRAME, + new Error(fmt("Unexpected frame on channel 0: %s", + inspect(f, false)))); + } + }; +} + +// This changed between versions, as did the codec, methods, etc. AMQP +// 0-9-1 is fairly similar to 0.8, but better, and nothing implements +// 0.8 that doesn't implement 0-9-1. In other words, it doesn't make +// much sense to generalise here. +C.sendProtocolHeader = function() { + this.sendBytes(frame.PROTOCOL_HEADER); +}; + +/* + The frighteningly complicated opening protocol (spec section 2.2.4): + + Client -> Server + + protocol header -> + <- start + start-ok -> + .. next two zero or more times .. + <- secure + secure-ok -> + <- tune + tune-ok -> + open -> + <- open-ok + +If I'm only supporting SASL's PLAIN mechanism (which I am for the time +being), it gets a bit easier since the server won't in general send +back a `secure`, it'll just send `tune` after the `start-ok`. +(SASL PLAIN: http://tools.ietf.org/html/rfc4616) + +*/ + +C.open = function(allFields, openCallback0) { + var self = this; + var openCallback = openCallback0 || function() {}; + + // This is where we'll put our negotiated values + var tunedOptions = Object.create(allFields); + + function wait(k) { + self.step(function(err, frame) { + if (err !== null) bail(err); + else if (frame.channel !== 0) { + bail(new Error( + fmt("Frame on channel != 0 during handshake: %s", + inspect(frame, false)))); + } + else k(frame); + }); + } + + function expect(Method, k) { + wait(function(frame) { + if (frame.id === Method) k(frame); + else { + bail(new Error( + fmt("Expected %s; got %s", + methodName(Method), inspect(frame, false)))); + } + }); + } + + function bail(err) { + openCallback(err); + } + + function send(Method) { + // This can throw an exception if there's some problem with the + // options; e.g., something is a string instead of a number. + try { self.sendMethod(0, Method, tunedOptions); } + catch (err) { bail(err); } + } + + function negotiate(server, desired) { + // We get sent values for channelMax, frameMax and heartbeat, + // which we may accept or lower (subject to a minimum for + // frameMax, but we'll leave that to the server to enforce). In + // all cases, `0` really means "no limit", or rather the highest + // value in the encoding, e.g., unsigned short for channelMax. + if (server === 0 || desired === 0) { + // i.e., whichever places a limit, if either + return Math.max(server, desired); + } + else { + return Math.min(server, desired); + } + } + + function onStart(start) { + var mechanisms = start.fields.mechanisms.toString().split(' '); + if (mechanisms.indexOf(allFields.mechanism) < 0) { + bail(new Error(fmt('SASL mechanism %s is not provided by the server', + allFields.mechanism))); + return; + } + self.serverProperties = start.fields.serverProperties; + send(defs.ConnectionStartOk); + wait(afterStartOk); + } + + function afterStartOk(reply) { + switch (reply.id) { + case defs.ConnectionSecure: + bail(new Error( + "Wasn't expecting to have to go through secure")); + break; + case defs.ConnectionClose: + bail(new Error(fmt("Handshake terminated by server: %s", + closeMsg(reply)))); + break; + case defs.ConnectionTune: + var fields = reply.fields; + tunedOptions.frameMax = + negotiate(fields.frameMax, allFields.frameMax); + tunedOptions.channelMax = + negotiate(fields.channelMax, allFields.channelMax); + tunedOptions.heartbeat = + negotiate(fields.heartbeat, allFields.heartbeat); + send(defs.ConnectionTuneOk); + send(defs.ConnectionOpen); + expect(defs.ConnectionOpenOk, onOpenOk); + break; + default: + bail(new Error( + fmt("Expected connection.secure, connection.close, " + + "or connection.tune during handshake; got %s", + inspect(reply, false)))); + break; + } + } + + function onOpenOk(openOk) { + // Impose the maximum of the encoded value, if the negotiated + // value is zero, meaning "no, no limits" + self.channelMax = tunedOptions.channelMax || 0xffff; + self.frameMax = tunedOptions.frameMax || 0xffffffff; + // 0 means "no heartbeat", rather than "maximum period of + // heartbeating" + self.heartbeat = tunedOptions.heartbeat; + self.heartbeater = self.startHeartbeater(); + self.accept = mainAccept; + succeed(openOk); + } + + // If the server closes the connection, it's probably because of + // something we did + function endWhileOpening(err) { + bail(err || new Error('Socket closed abruptly ' + + 'during opening handshake')); + } + + this.stream.on('end', endWhileOpening); + this.stream.on('error', endWhileOpening); + + function succeed(ok) { + self.stream.removeListener('end', endWhileOpening); + self.stream.removeListener('error', endWhileOpening); + self.stream.on('error', self.onSocketError.bind(self)); + self.stream.on('end', self.onSocketError.bind( + self, new Error('Unexpected close'))); + self.on('frameError', self.onSocketError.bind(self)); + self.acceptLoop(); + openCallback(null, ok); + } + + // Now kick off the handshake by prompting the server + this.sendProtocolHeader(); + expect(defs.ConnectionStart, onStart); +}; + +// Closing things: AMQP has a closing handshake that applies to +// closing both connects and channels. As the initiating party, I send +// Close, then ignore all frames until I see either CloseOK -- +// which signifies that the other party has seen the Close and shut +// the connection or channel down, so it's fine to free resources; or +// Close, which means the other party also wanted to close the +// whatever, and I should send CloseOk so it can free resources, +// then go back to waiting for the CloseOk. If I receive a Close +// out of the blue, I should throw away any unsent frames (they will +// be ignored anyway) and send CloseOk, then clean up resources. In +// general, Close out of the blue signals an error (or a forced +// closure, which may as well be an error). +// +// RUNNING [1] --- send Close ---> Closing [2] ---> recv Close --+ +// | | [3] +// | +------ send CloseOk ------+ +// recv Close recv CloseOk +// | | +// V V +// Ended [4] ---- send CloseOk ---> Closed [5] +// +// [1] All frames accepted; getting a Close frame from the server +// moves to Ended; client may initiate a close by sending Close +// itself. +// [2] Client has initiated a close; only CloseOk or (simulataneously +// sent) Close is accepted. +// [3] Simultaneous close +// [4] Server won't send any more frames; accept no more frames, send +// CloseOk. +// [5] Fully closed, client will send no more, server will send no +// more. Signal 'close' or 'error'. +// +// There are two signalling mechanisms used in the API. The first is +// that calling `close` will return a promise, that will either +// resolve once the connection or channel is cleanly shut down, or +// will reject if the shutdown times out. +// +// The second is the 'close' and 'error' events. These are +// emitted as above. The events will fire *before* promises are +// resolved. + +// Close the connection without even giving a reason. Typical. +C.close = function(closeCallback) { + var k = closeCallback && function() { closeCallback(null); }; + this.closeBecause("Cheers, thanks", constants.REPLY_SUCCESS, k); +}; + +// Close with a reason and a 'code'. I'm pretty sure RabbitMQ totally +// ignores these; maybe it logs them. The continuation will be invoked +// when the CloseOk has been received, and before the 'close' event. +C.closeBecause = function(reason, code, k) { + this.sendMethod(0, defs.ConnectionClose, { + replyText: reason, + replyCode: code, + methodId: 0, classId: 0 + }); + var s = stackCapture('closeBecause called: ' + reason); + this.toClosing(s, k); +}; + +C.closeWithError = function(reason, code, error) { + this.emit('error', error); + this.closeBecause(reason, code); +}; + +C.onSocketError = function(err) { + if (!this.expectSocketClose) { + // forestall any more calls to onSocketError, since we're signed + // up for `'error'` *and* `'end'` + this.expectSocketClose = true; + this.emit('error', err); + var s = stackCapture('Socket error'); + this.toClosed(s, err); + } +}; + +function invalidOp(msg, stack) { + return function() { + throw new IllegalOperationError(msg, stack); + }; +} + +function invalidateSend(conn, msg, stack) { + conn.sendMethod = conn.sendContent = conn.sendMessage = + invalidOp(msg, stack); +} + +// A close has been initiated. Repeat: a close has been initiated. +// This means we should not send more frames, anyway they will be +// ignored. We also have to shut down all the channels. +C.toClosing = function(capturedStack, k) { + var send = this.sendMethod.bind(this); + + this.accept = function(f) { + if (f.id === defs.ConnectionCloseOk) { + if (k) k(); + var s = stackCapture('ConnectionCloseOk received'); + this.toClosed(s, undefined); + } + else if (f.id === defs.ConnectionClose) { + send(0, defs.ConnectionCloseOk, {}); + } + // else ignore frame + }; + invalidateSend(this, 'Connection closing', capturedStack); +}; + +C._closeChannels = function(capturedStack) { + for (var i = 1; i < this.channels.length; i++) { + var ch = this.channels[i]; + if (ch !== null) { + ch.channel.toClosed(capturedStack); // %%% or with an error? not clear + } + } +}; + +// A close has been confirmed. Cease all communication. +C.toClosed = function(capturedStack, maybeErr) { + this._closeChannels(capturedStack); + var info = fmt('Connection closed (%s)', + (maybeErr) ? maybeErr.toString() : 'by client'); + // Tidy up, invalidate enverything, dynamite the bridges. + invalidateSend(this, info, capturedStack); + this.accept = invalidOp(info, capturedStack); + this.close = function(cb) { + cb && cb(new IllegalOperationError(info, capturedStack)); + }; + if (this.heartbeater) this.heartbeater.clear(); + // This is certainly true now, if it wasn't before + this.expectSocketClose = true; + this.stream.end(); + this.emit('close', maybeErr); +}; + +// === + +C.startHeartbeater = function() { + if (this.heartbeat === 0) return null; + else { + var self = this; + var hb = new Heart(this.heartbeat, + this.checkSend.bind(this), + this.checkRecv.bind(this)); + hb.on('timeout', function() { + var hberr = new Error("Heartbeat timeout"); + self.emit('error', hberr); + var s = stackCapture('Heartbeat timeout'); + self.toClosed(s, hberr); + }); + hb.on('beat', function() { + self.sendHeartbeat(); + }); + return hb; + } +}; + +// I use an array to keep track of the channels, rather than an +// object. The channel identifiers are numbers, and allocated by the +// connection. If I try to allocate low numbers when they are +// available (which I do, by looking from the start of the bitset), +// this ought to keep the array small, and out of 'sparse array +// storage'. I also set entries to null, rather than deleting them, in +// the expectation that the next channel allocation will fill the slot +// again rather than growing the array. See +// http://www.html5rocks.com/en/tutorials/speed/v8/ +C.freshChannel = function(channel, options) { + var next = this.freeChannels.nextClearBit(1); + if (next < 0 || next > this.channelMax) + throw new Error("No channels left to allocate"); + this.freeChannels.set(next); + + var hwm = (options && options.highWaterMark) || DEFAULT_WRITE_HWM; + var writeBuffer = new PassThrough({ + objectMode: true, highWaterMark: hwm + }); + this.channels[next] = {channel: channel, buffer: writeBuffer}; + writeBuffer.on('drain', function() { + channel.onBufferDrain(); + }); + this.muxer.pipeFrom(writeBuffer); + return next; +}; + +C.releaseChannel = function(channel) { + this.freeChannels.clear(channel); + var buffer = this.channels[channel].buffer; + buffer.end(); // will also cause it to be unpiped + this.channels[channel] = null; +}; + +C.acceptLoop = function() { + var self = this; + + function go() { + try { + var f; while (f = self.recvFrame()) self.accept(f); + } + catch (e) { + self.emit('frameError', e); + } + } + self.stream.on('readable', go); + go(); +}; + +C.step = function(cb) { + var self = this; + function recv() { + var f; + try { + f = self.recvFrame(); + } + catch (e) { + cb(e, null); + return; + } + if (f) cb(null, f); + else self.stream.once('readable', recv); + } + recv(); +}; + +C.checkSend = function() { + var check = this.sentSinceLastCheck; + this.sentSinceLastCheck = false; + return check; +} + +C.checkRecv = function() { + var check = this.recvSinceLastCheck; + this.recvSinceLastCheck = false; + return check; +} + +C.sendBytes = function(bytes) { + this.sentSinceLastCheck = true; + this.stream.write(bytes); +}; + +C.sendHeartbeat = function() { + return this.sendBytes(frame.HEARTBEAT_BUF); +}; + +var encodeMethod = defs.encodeMethod; +var encodeProperties = defs.encodeProperties; + +C.sendMethod = function(channel, Method, fields) { + var frame = encodeMethod(Method, channel, fields); + this.sentSinceLastCheck = true; + var buffer = this.channels[channel].buffer; + return buffer.write(frame); +}; + +C.sendMessage = function(channel, + Method, fields, + Properties, props, + content) { + if (!Buffer.isBuffer(content)) + throw new TypeError('content is not a buffer'); + + var mframe = encodeMethod(Method, channel, fields); + var pframe = encodeProperties(Properties, channel, + content.length, props); + var buffer = this.channels[channel].buffer; + this.sentSinceLastCheck = true; + + var methodHeaderLen = mframe.length + pframe.length; + var bodyLen = (content.length > 0) ? + content.length + FRAME_OVERHEAD : 0; + var allLen = methodHeaderLen + bodyLen; + + if (allLen < SINGLE_CHUNK_THRESHOLD) { + var all = Buffer.alloc(allLen); + var offset = mframe.copy(all, 0); + offset += pframe.copy(all, offset); + + if (bodyLen > 0) + makeBodyFrame(channel, content).copy(all, offset); + return buffer.write(all); + } + else { + if (methodHeaderLen < SINGLE_CHUNK_THRESHOLD) { + var both = Buffer.alloc(methodHeaderLen); + var offset = mframe.copy(both, 0); + pframe.copy(both, offset); + buffer.write(both); + } + else { + buffer.write(mframe); + buffer.write(pframe); + } + return this.sendContent(channel, content); + } +}; + +var FRAME_OVERHEAD = defs.FRAME_OVERHEAD; +var makeBodyFrame = frame.makeBodyFrame; + +C.sendContent = function(channel, body) { + if (!Buffer.isBuffer(body)) { + throw new TypeError(fmt("Expected buffer; got %s", body)); + } + var writeResult = true; + var buffer = this.channels[channel].buffer; + + var maxBody = this.frameMax - FRAME_OVERHEAD; + + for (var offset = 0; offset < body.length; offset += maxBody) { + var end = offset + maxBody; + var slice = (end > body.length) ? body.slice(offset) : body.slice(offset, end); + var bodyFrame = makeBodyFrame(channel, slice); + writeResult = buffer.write(bodyFrame); + } + this.sentSinceLastCheck = true; + return writeResult; +}; + +var parseFrame = frame.parseFrame; +var decodeFrame = frame.decodeFrame; + +C.recvFrame = function() { + // %%% identifying invariants might help here? + var frame = parseFrame(this.rest, this.frameMax); + + if (!frame) { + var incoming = this.stream.read(); + if (incoming === null) { + return false; + } + else { + this.recvSinceLastCheck = true; + this.rest = Buffer.concat([this.rest, incoming]); + return this.recvFrame(); + } + } + else { + this.rest = frame.rest; + return decodeFrame(frame); + } +}; + +function wrapStream(s) { + if (s instanceof Duplex) return s; + else { + var ws = new Duplex(); + ws.wrap(s); //wraps the readable side of things + ws._write = function(chunk, encoding, callback) { + return s.write(chunk, encoding, callback); + }; + return ws; + } +} + +function isFatalError(error) { + switch (error && error.code) { + case defs.constants.CONNECTION_FORCED: + case defs.constants.REPLY_SUCCESS: + return false; + default: + return true; + } +} + +module.exports.Connection = Connection; +module.exports.isFatalError = isFatalError; diff --git a/node_modules/amqplib/lib/credentials.js b/node_modules/amqplib/lib/credentials.js new file mode 100644 index 0000000..38a8053 --- /dev/null +++ b/node_modules/amqplib/lib/credentials.js @@ -0,0 +1,43 @@ +// +// +// + +// Different kind of credentials that can be supplied when opening a +// connection, corresponding to SASL mechanisms There's only two +// useful mechanisms that RabbitMQ implements: +// * PLAIN (send username and password in the plain) +// * EXTERNAL (assume the server will figure out who you are from +// context, i.e., your SSL certificate) +var Buffer = require('safe-buffer').Buffer +var codec = require('./codec') + +module.exports.plain = function(user, passwd) { + return { + mechanism: 'PLAIN', + response: function() { + return Buffer.from(['', user, passwd].join(String.fromCharCode(0))) + }, + username: user, + password: passwd + } +} + +module.exports.amqplain = function(user, passwd) { + return { + mechanism: 'AMQPLAIN', + response: function() { + const buffer = Buffer.alloc(16384); + const size = codec.encodeTable(buffer, { LOGIN: user, PASSWORD: passwd}, 0); + return buffer.slice(4, size); + }, + username: user, + password: passwd + } +} + +module.exports.external = function() { + return { + mechanism: 'EXTERNAL', + response: function() { return Buffer.from(''); } + } +} diff --git a/node_modules/amqplib/lib/defs.js b/node_modules/amqplib/lib/defs.js new file mode 100644 index 0000000..ef5cd0a --- /dev/null +++ b/node_modules/amqplib/lib/defs.js @@ -0,0 +1,4966 @@ +/** @preserve This file is generated by the script + * ../bin/generate-defs.js, which is not in general included in a + * distribution, but is available in the source repository e.g. at + * https://github.com/squaremo/amqp.node/ + */ +"use strict"; + +function decodeConnectionStart(buffer) { + var val, len, offset = 0, fields = { + versionMajor: void 0, + versionMinor: void 0, + serverProperties: void 0, + mechanisms: void 0, + locales: void 0 + }; + val = buffer[offset]; + offset++; + fields.versionMajor = val; + val = buffer[offset]; + offset++; + fields.versionMinor = val; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.serverProperties = val; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.mechanisms = val; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.locales = val; + return fields; +} + +function encodeConnectionStart(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + val = fields.serverProperties; + if (void 0 === val) throw new Error("Missing value for mandatory field 'serverProperties'"); + if ("object" != typeof val) throw new TypeError("Field 'serverProperties' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var serverProperties_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += serverProperties_encoded.length; + val = fields.mechanisms; + if (void 0 === val) val = Buffer.from("PLAIN"); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'mechanisms' is the wrong type; must be a Buffer"); + varyingSize += val.length; + val = fields.locales; + if (void 0 === val) val = Buffer.from("en_US"); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'locales' is the wrong type; must be a Buffer"); + varyingSize += val.length; + var buffer = Buffer.alloc(22 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655370, 7); + offset = 11; + val = fields.versionMajor; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'versionMajor' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt8(val, offset); + offset++; + val = fields.versionMinor; + if (void 0 === val) val = 9; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'versionMinor' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt8(val, offset); + offset++; + offset += serverProperties_encoded.copy(buffer, offset); + val = fields.mechanisms; + void 0 === val && (val = Buffer.from("PLAIN")); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + val = fields.locales; + void 0 === val && (val = Buffer.from("en_US")); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionStartOk(buffer) { + var val, len, offset = 0, fields = { + clientProperties: void 0, + mechanism: void 0, + response: void 0, + locale: void 0 + }; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.clientProperties = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.mechanism = val; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.response = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.locale = val; + return fields; +} + +function encodeConnectionStartOk(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + val = fields.clientProperties; + if (void 0 === val) throw new Error("Missing value for mandatory field 'clientProperties'"); + if ("object" != typeof val) throw new TypeError("Field 'clientProperties' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var clientProperties_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += clientProperties_encoded.length; + val = fields.mechanism; + if (void 0 === val) val = "PLAIN"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'mechanism' is the wrong type; must be a string (up to 255 chars)"); + var mechanism_len = Buffer.byteLength(val, "utf8"); + varyingSize += mechanism_len; + val = fields.response; + if (void 0 === val) throw new Error("Missing value for mandatory field 'response'"); + if (!Buffer.isBuffer(val)) throw new TypeError("Field 'response' is the wrong type; must be a Buffer"); + varyingSize += val.length; + val = fields.locale; + if (void 0 === val) val = "en_US"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'locale' is the wrong type; must be a string (up to 255 chars)"); + var locale_len = Buffer.byteLength(val, "utf8"); + varyingSize += locale_len; + var buffer = Buffer.alloc(18 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655371, 7); + offset = 11; + offset += clientProperties_encoded.copy(buffer, offset); + val = fields.mechanism; + void 0 === val && (val = "PLAIN"); + buffer[offset] = mechanism_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += mechanism_len; + val = fields.response; + void 0 === val && (val = Buffer.from(void 0)); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + val = fields.locale; + void 0 === val && (val = "en_US"); + buffer[offset] = locale_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += locale_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionSecure(buffer) { + var val, len, offset = 0, fields = { + challenge: void 0 + }; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.challenge = val; + return fields; +} + +function encodeConnectionSecure(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0; + val = fields.challenge; + if (void 0 === val) throw new Error("Missing value for mandatory field 'challenge'"); + if (!Buffer.isBuffer(val)) throw new TypeError("Field 'challenge' is the wrong type; must be a Buffer"); + varyingSize += val.length; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655380, 7); + offset = 11; + val = fields.challenge; + void 0 === val && (val = Buffer.from(void 0)); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionSecureOk(buffer) { + var val, len, offset = 0, fields = { + response: void 0 + }; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.response = val; + return fields; +} + +function encodeConnectionSecureOk(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0; + val = fields.response; + if (void 0 === val) throw new Error("Missing value for mandatory field 'response'"); + if (!Buffer.isBuffer(val)) throw new TypeError("Field 'response' is the wrong type; must be a Buffer"); + varyingSize += val.length; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655381, 7); + offset = 11; + val = fields.response; + void 0 === val && (val = Buffer.from(void 0)); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionTune(buffer) { + var val, offset = 0, fields = { + channelMax: void 0, + frameMax: void 0, + heartbeat: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.channelMax = val; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.frameMax = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.heartbeat = val; + return fields; +} + +function encodeConnectionTune(channel, fields) { + var offset = 0, val = null, buffer = Buffer.alloc(20); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655390, 7); + offset = 11; + val = fields.channelMax; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.frameMax; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + val = fields.heartbeat; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionTuneOk(buffer) { + var val, offset = 0, fields = { + channelMax: void 0, + frameMax: void 0, + heartbeat: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.channelMax = val; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.frameMax = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.heartbeat = val; + return fields; +} + +function encodeConnectionTuneOk(channel, fields) { + var offset = 0, val = null, buffer = Buffer.alloc(20); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655391, 7); + offset = 11; + val = fields.channelMax; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.frameMax; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + val = fields.heartbeat; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionOpen(buffer) { + var val, len, offset = 0, fields = { + virtualHost: void 0, + capabilities: void 0, + insist: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.virtualHost = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.capabilities = val; + val = !!(1 & buffer[offset]); + fields.insist = val; + return fields; +} + +function encodeConnectionOpen(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.virtualHost; + if (void 0 === val) val = "/"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'virtualHost' is the wrong type; must be a string (up to 255 chars)"); + var virtualHost_len = Buffer.byteLength(val, "utf8"); + varyingSize += virtualHost_len; + val = fields.capabilities; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'capabilities' is the wrong type; must be a string (up to 255 chars)"); + var capabilities_len = Buffer.byteLength(val, "utf8"); + varyingSize += capabilities_len; + var buffer = Buffer.alloc(15 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655400, 7); + offset = 11; + val = fields.virtualHost; + void 0 === val && (val = "/"); + buffer[offset] = virtualHost_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += virtualHost_len; + val = fields.capabilities; + void 0 === val && (val = ""); + buffer[offset] = capabilities_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += capabilities_len; + val = fields.insist; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionOpenOk(buffer) { + var val, len, offset = 0, fields = { + knownHosts: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.knownHosts = val; + return fields; +} + +function encodeConnectionOpenOk(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.knownHosts; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'knownHosts' is the wrong type; must be a string (up to 255 chars)"); + var knownHosts_len = Buffer.byteLength(val, "utf8"); + varyingSize += knownHosts_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655401, 7); + offset = 11; + val = fields.knownHosts; + void 0 === val && (val = ""); + buffer[offset] = knownHosts_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += knownHosts_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionClose(buffer) { + var val, len, offset = 0, fields = { + replyCode: void 0, + replyText: void 0, + classId: void 0, + methodId: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.replyCode = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.replyText = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.classId = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.methodId = val; + return fields; +} + +function encodeConnectionClose(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.replyText; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, "utf8"); + varyingSize += replyText_len; + var buffer = Buffer.alloc(19 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655410, 7); + offset = 11; + val = fields.replyCode; + if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.replyText; + void 0 === val && (val = ""); + buffer[offset] = replyText_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += replyText_len; + val = fields.classId; + if (void 0 === val) throw new Error("Missing value for mandatory field 'classId'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.methodId; + if (void 0 === val) throw new Error("Missing value for mandatory field 'methodId'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionCloseOk(buffer) { + return {}; +} + +function encodeConnectionCloseOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655411, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionBlocked(buffer) { + var val, len, offset = 0, fields = { + reason: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.reason = val; + return fields; +} + +function encodeConnectionBlocked(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.reason; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)"); + var reason_len = Buffer.byteLength(val, "utf8"); + varyingSize += reason_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655420, 7); + offset = 11; + val = fields.reason; + void 0 === val && (val = ""); + buffer[offset] = reason_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += reason_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConnectionUnblocked(buffer) { + return {}; +} + +function encodeConnectionUnblocked(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(655421, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelOpen(buffer) { + var val, len, offset = 0, fields = { + outOfBand: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.outOfBand = val; + return fields; +} + +function encodeChannelOpen(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.outOfBand; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'outOfBand' is the wrong type; must be a string (up to 255 chars)"); + var outOfBand_len = Buffer.byteLength(val, "utf8"); + varyingSize += outOfBand_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310730, 7); + offset = 11; + val = fields.outOfBand; + void 0 === val && (val = ""); + buffer[offset] = outOfBand_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += outOfBand_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelOpenOk(buffer) { + var val, len, offset = 0, fields = { + channelId: void 0 + }; + len = buffer.readUInt32BE(offset); + offset += 4; + val = buffer.slice(offset, offset + len); + offset += len; + fields.channelId = val; + return fields; +} + +function encodeChannelOpenOk(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0; + val = fields.channelId; + if (void 0 === val) val = Buffer.from(""); else if (!Buffer.isBuffer(val)) throw new TypeError("Field 'channelId' is the wrong type; must be a Buffer"); + varyingSize += val.length; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310731, 7); + offset = 11; + val = fields.channelId; + void 0 === val && (val = Buffer.from("")); + len = val.length; + buffer.writeUInt32BE(len, offset); + offset += 4; + val.copy(buffer, offset); + offset += len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelFlow(buffer) { + var val, fields = { + active: void 0 + }; + val = !!(1 & buffer[0]); + fields.active = val; + return fields; +} + +function encodeChannelFlow(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310740, 7); + offset = 11; + val = fields.active; + if (void 0 === val) throw new Error("Missing value for mandatory field 'active'"); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelFlowOk(buffer) { + var val, fields = { + active: void 0 + }; + val = !!(1 & buffer[0]); + fields.active = val; + return fields; +} + +function encodeChannelFlowOk(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310741, 7); + offset = 11; + val = fields.active; + if (void 0 === val) throw new Error("Missing value for mandatory field 'active'"); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelClose(buffer) { + var val, len, offset = 0, fields = { + replyCode: void 0, + replyText: void 0, + classId: void 0, + methodId: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.replyCode = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.replyText = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.classId = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.methodId = val; + return fields; +} + +function encodeChannelClose(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.replyText; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, "utf8"); + varyingSize += replyText_len; + var buffer = Buffer.alloc(19 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310760, 7); + offset = 11; + val = fields.replyCode; + if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.replyText; + void 0 === val && (val = ""); + buffer[offset] = replyText_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += replyText_len; + val = fields.classId; + if (void 0 === val) throw new Error("Missing value for mandatory field 'classId'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.methodId; + if (void 0 === val) throw new Error("Missing value for mandatory field 'methodId'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeChannelCloseOk(buffer) { + return {}; +} + +function encodeChannelCloseOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1310761, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeAccessRequest(buffer) { + var val, len, offset = 0, fields = { + realm: void 0, + exclusive: void 0, + passive: void 0, + active: void 0, + write: void 0, + read: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.realm = val; + val = !!(1 & buffer[offset]); + fields.exclusive = val; + val = !!(2 & buffer[offset]); + fields.passive = val; + val = !!(4 & buffer[offset]); + fields.active = val; + val = !!(8 & buffer[offset]); + fields.write = val; + val = !!(16 & buffer[offset]); + fields.read = val; + return fields; +} + +function encodeAccessRequest(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.realm; + if (void 0 === val) val = "/data"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'realm' is the wrong type; must be a string (up to 255 chars)"); + var realm_len = Buffer.byteLength(val, "utf8"); + varyingSize += realm_len; + var buffer = Buffer.alloc(14 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1966090, 7); + offset = 11; + val = fields.realm; + void 0 === val && (val = "/data"); + buffer[offset] = realm_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += realm_len; + val = fields.exclusive; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.passive; + void 0 === val && (val = !0); + val && (bits += 2); + val = fields.active; + void 0 === val && (val = !0); + val && (bits += 4); + val = fields.write; + void 0 === val && (val = !0); + val && (bits += 8); + val = fields.read; + void 0 === val && (val = !0); + val && (bits += 16); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeAccessRequestOk(buffer) { + var val, offset = 0, fields = { + ticket: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + return fields; +} + +function encodeAccessRequestOk(channel, fields) { + var offset = 0, val = null, buffer = Buffer.alloc(14); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(1966091, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 1; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeDeclare(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + exchange: void 0, + type: void 0, + passive: void 0, + durable: void 0, + autoDelete: void 0, + internal: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.type = val; + val = !!(1 & buffer[offset]); + fields.passive = val; + val = !!(2 & buffer[offset]); + fields.durable = val; + val = !!(4 & buffer[offset]); + fields.autoDelete = val; + val = !!(8 & buffer[offset]); + fields.internal = val; + val = !!(16 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeExchangeDeclare(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.type; + if (void 0 === val) val = "direct"; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); + var type_len = Buffer.byteLength(val, "utf8"); + varyingSize += type_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(17 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621450, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.type; + void 0 === val && (val = "direct"); + buffer[offset] = type_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += type_len; + val = fields.passive; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.durable; + void 0 === val && (val = !1); + val && (bits += 2); + val = fields.autoDelete; + void 0 === val && (val = !1); + val && (bits += 4); + val = fields.internal; + void 0 === val && (val = !1); + val && (bits += 8); + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 16); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeDeclareOk(buffer) { + return {}; +} + +function encodeExchangeDeclareOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621451, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeDelete(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + exchange: void 0, + ifUnused: void 0, + nowait: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + val = !!(1 & buffer[offset]); + fields.ifUnused = val; + val = !!(2 & buffer[offset]); + fields.nowait = val; + return fields; +} + +function encodeExchangeDelete(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621460, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.ifUnused; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 2); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeDeleteOk(buffer) { + return {}; +} + +function encodeExchangeDeleteOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621461, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeBind(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + destination: void 0, + source: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.destination = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.source = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + val = !!(1 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeExchangeBind(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.destination; + if (void 0 === val) throw new Error("Missing value for mandatory field 'destination'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); + var destination_len = Buffer.byteLength(val, "utf8"); + varyingSize += destination_len; + val = fields.source; + if (void 0 === val) throw new Error("Missing value for mandatory field 'source'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); + var source_len = Buffer.byteLength(val, "utf8"); + varyingSize += source_len; + val = fields.routingKey; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(18 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621470, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.destination; + void 0 === val && (val = void 0); + buffer[offset] = destination_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += destination_len; + val = fields.source; + void 0 === val && (val = void 0); + buffer[offset] = source_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += source_len; + val = fields.routingKey; + void 0 === val && (val = ""); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeBindOk(buffer) { + return {}; +} + +function encodeExchangeBindOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621471, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeUnbind(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + destination: void 0, + source: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.destination = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.source = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + val = !!(1 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeExchangeUnbind(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.destination; + if (void 0 === val) throw new Error("Missing value for mandatory field 'destination'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)"); + var destination_len = Buffer.byteLength(val, "utf8"); + varyingSize += destination_len; + val = fields.source; + if (void 0 === val) throw new Error("Missing value for mandatory field 'source'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)"); + var source_len = Buffer.byteLength(val, "utf8"); + varyingSize += source_len; + val = fields.routingKey; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(18 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621480, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.destination; + void 0 === val && (val = void 0); + buffer[offset] = destination_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += destination_len; + val = fields.source; + void 0 === val && (val = void 0); + buffer[offset] = source_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += source_len; + val = fields.routingKey; + void 0 === val && (val = ""); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeExchangeUnbindOk(buffer) { + return {}; +} + +function encodeExchangeUnbindOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(2621491, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueDeclare(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + passive: void 0, + durable: void 0, + exclusive: void 0, + autoDelete: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + val = !!(1 & buffer[offset]); + fields.passive = val; + val = !!(2 & buffer[offset]); + fields.durable = val; + val = !!(4 & buffer[offset]); + fields.exclusive = val; + val = !!(8 & buffer[offset]); + fields.autoDelete = val; + val = !!(16 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeQueueDeclare(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276810, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.passive; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.durable; + void 0 === val && (val = !1); + val && (bits += 2); + val = fields.exclusive; + void 0 === val && (val = !1); + val && (bits += 4); + val = fields.autoDelete; + void 0 === val && (val = !1); + val && (bits += 8); + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 16); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueDeclareOk(buffer) { + var val, len, offset = 0, fields = { + queue: void 0, + messageCount: void 0, + consumerCount: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.messageCount = val; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.consumerCount = val; + return fields; +} + +function encodeQueueDeclareOk(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.queue; + if (void 0 === val) throw new Error("Missing value for mandatory field 'queue'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + var buffer = Buffer.alloc(21 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276811, 7); + offset = 11; + val = fields.queue; + void 0 === val && (val = void 0); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.messageCount; + if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + val = fields.consumerCount; + if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerCount'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'consumerCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueBind(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + exchange: void 0, + routingKey: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + val = !!(1 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeQueueBind(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(18 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276820, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = ""); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueBindOk(buffer) { + return {}; +} + +function encodeQueueBindOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276821, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueuePurge(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + nowait: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + val = !!(1 & buffer[offset]); + fields.nowait = val; + return fields; +} + +function encodeQueuePurge(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276830, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueuePurgeOk(buffer) { + var val, offset = 0, fields = { + messageCount: void 0 + }; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.messageCount = val; + return fields; +} + +function encodeQueuePurgeOk(channel, fields) { + var offset = 0, val = null, buffer = Buffer.alloc(16); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276831, 7); + offset = 11; + val = fields.messageCount; + if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueDelete(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + ifUnused: void 0, + ifEmpty: void 0, + nowait: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + val = !!(1 & buffer[offset]); + fields.ifUnused = val; + val = !!(2 & buffer[offset]); + fields.ifEmpty = val; + val = !!(4 & buffer[offset]); + fields.nowait = val; + return fields; +} + +function encodeQueueDelete(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276840, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.ifUnused; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.ifEmpty; + void 0 === val && (val = !1); + val && (bits += 2); + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 4); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueDeleteOk(buffer) { + var val, offset = 0, fields = { + messageCount: void 0 + }; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.messageCount = val; + return fields; +} + +function encodeQueueDeleteOk(channel, fields) { + var offset = 0, val = null, buffer = Buffer.alloc(16); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276841, 7); + offset = 11; + val = fields.messageCount; + if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueUnbind(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + exchange: void 0, + routingKey: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeQueueUnbind(channel, fields) { + var len, offset = 0, val = null, varyingSize = 0, scratchOffset = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(17 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276850, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = ""); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeQueueUnbindOk(buffer) { + return {}; +} + +function encodeQueueUnbindOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3276851, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicQos(buffer) { + var val, offset = 0, fields = { + prefetchSize: void 0, + prefetchCount: void 0, + global: void 0 + }; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.prefetchSize = val; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.prefetchCount = val; + val = !!(1 & buffer[offset]); + fields.global = val; + return fields; +} + +function encodeBasicQos(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(19); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932170, 7); + offset = 11; + val = fields.prefetchSize; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'prefetchSize' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + val = fields.prefetchCount; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'prefetchCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.global; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicQosOk(buffer) { + return {}; +} + +function encodeBasicQosOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932171, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicConsume(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + consumerTag: void 0, + noLocal: void 0, + noAck: void 0, + exclusive: void 0, + nowait: void 0, + arguments: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.consumerTag = val; + val = !!(1 & buffer[offset]); + fields.noLocal = val; + val = !!(2 & buffer[offset]); + fields.noAck = val; + val = !!(4 & buffer[offset]); + fields.exclusive = val; + val = !!(8 & buffer[offset]); + fields.nowait = val; + offset++; + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.arguments = val; + return fields; +} + +function encodeBasicConsume(channel, fields) { + var len, offset = 0, val = null, bits = 0, varyingSize = 0, scratchOffset = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + val = fields.consumerTag; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, "utf8"); + varyingSize += consumerTag_len; + val = fields.arguments; + if (void 0 === val) val = {}; else if ("object" != typeof val) throw new TypeError("Field 'arguments' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var arguments_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += arguments_encoded.length; + var buffer = Buffer.alloc(17 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932180, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.consumerTag; + void 0 === val && (val = ""); + buffer[offset] = consumerTag_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += consumerTag_len; + val = fields.noLocal; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.noAck; + void 0 === val && (val = !1); + val && (bits += 2); + val = fields.exclusive; + void 0 === val && (val = !1); + val && (bits += 4); + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 8); + buffer[offset] = bits; + offset++; + bits = 0; + offset += arguments_encoded.copy(buffer, offset); + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicConsumeOk(buffer) { + var val, len, offset = 0, fields = { + consumerTag: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.consumerTag = val; + return fields; +} + +function encodeBasicConsumeOk(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.consumerTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, "utf8"); + varyingSize += consumerTag_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932181, 7); + offset = 11; + val = fields.consumerTag; + void 0 === val && (val = void 0); + buffer[offset] = consumerTag_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += consumerTag_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicCancel(buffer) { + var val, len, offset = 0, fields = { + consumerTag: void 0, + nowait: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.consumerTag = val; + val = !!(1 & buffer[offset]); + fields.nowait = val; + return fields; +} + +function encodeBasicCancel(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.consumerTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, "utf8"); + varyingSize += consumerTag_len; + var buffer = Buffer.alloc(14 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932190, 7); + offset = 11; + val = fields.consumerTag; + void 0 === val && (val = void 0); + buffer[offset] = consumerTag_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += consumerTag_len; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicCancelOk(buffer) { + var val, len, offset = 0, fields = { + consumerTag: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.consumerTag = val; + return fields; +} + +function encodeBasicCancelOk(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.consumerTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, "utf8"); + varyingSize += consumerTag_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932191, 7); + offset = 11; + val = fields.consumerTag; + void 0 === val && (val = void 0); + buffer[offset] = consumerTag_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += consumerTag_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicPublish(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + exchange: void 0, + routingKey: void 0, + mandatory: void 0, + immediate: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + val = !!(1 & buffer[offset]); + fields.mandatory = val; + val = !!(2 & buffer[offset]); + fields.immediate = val; + return fields; +} + +function encodeBasicPublish(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.exchange; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + var buffer = Buffer.alloc(17 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932200, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.exchange; + void 0 === val && (val = ""); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = ""); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + val = fields.mandatory; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.immediate; + void 0 === val && (val = !1); + val && (bits += 2); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicReturn(buffer) { + var val, len, offset = 0, fields = { + replyCode: void 0, + replyText: void 0, + exchange: void 0, + routingKey: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.replyCode = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.replyText = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + return fields; +} + +function encodeBasicReturn(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.replyText; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)"); + var replyText_len = Buffer.byteLength(val, "utf8"); + varyingSize += replyText_len; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + var buffer = Buffer.alloc(17 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932210, 7); + offset = 11; + val = fields.replyCode; + if (void 0 === val) throw new Error("Missing value for mandatory field 'replyCode'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.replyText; + void 0 === val && (val = ""); + buffer[offset] = replyText_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += replyText_len; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = void 0); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicDeliver(buffer) { + var val, len, offset = 0, fields = { + consumerTag: void 0, + deliveryTag: void 0, + redelivered: void 0, + exchange: void 0, + routingKey: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.consumerTag = val; + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.deliveryTag = val; + val = !!(1 & buffer[offset]); + fields.redelivered = val; + offset++; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + return fields; +} + +function encodeBasicDeliver(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.consumerTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'consumerTag'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)"); + var consumerTag_len = Buffer.byteLength(val, "utf8"); + varyingSize += consumerTag_len; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + var buffer = Buffer.alloc(24 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932220, 7); + offset = 11; + val = fields.consumerTag; + void 0 === val && (val = void 0); + buffer[offset] = consumerTag_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += consumerTag_len; + val = fields.deliveryTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + val = fields.redelivered; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + bits = 0; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = void 0); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicGet(buffer) { + var val, len, offset = 0, fields = { + ticket: void 0, + queue: void 0, + noAck: void 0 + }; + val = buffer.readUInt16BE(offset); + offset += 2; + fields.ticket = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.queue = val; + val = !!(1 & buffer[offset]); + fields.noAck = val; + return fields; +} + +function encodeBasicGet(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.queue; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)"); + var queue_len = Buffer.byteLength(val, "utf8"); + varyingSize += queue_len; + var buffer = Buffer.alloc(16 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932230, 7); + offset = 11; + val = fields.ticket; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt16BE(val, offset); + offset += 2; + val = fields.queue; + void 0 === val && (val = ""); + buffer[offset] = queue_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += queue_len; + val = fields.noAck; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicGetOk(buffer) { + var val, len, offset = 0, fields = { + deliveryTag: void 0, + redelivered: void 0, + exchange: void 0, + routingKey: void 0, + messageCount: void 0 + }; + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.deliveryTag = val; + val = !!(1 & buffer[offset]); + fields.redelivered = val; + offset++; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.exchange = val; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.routingKey = val; + val = buffer.readUInt32BE(offset); + offset += 4; + fields.messageCount = val; + return fields; +} + +function encodeBasicGetOk(channel, fields) { + var offset = 0, val = null, bits = 0, varyingSize = 0; + val = fields.exchange; + if (void 0 === val) throw new Error("Missing value for mandatory field 'exchange'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)"); + var exchange_len = Buffer.byteLength(val, "utf8"); + varyingSize += exchange_len; + val = fields.routingKey; + if (void 0 === val) throw new Error("Missing value for mandatory field 'routingKey'"); + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)"); + var routingKey_len = Buffer.byteLength(val, "utf8"); + varyingSize += routingKey_len; + var buffer = Buffer.alloc(27 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932231, 7); + offset = 11; + val = fields.deliveryTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + val = fields.redelivered; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + bits = 0; + val = fields.exchange; + void 0 === val && (val = void 0); + buffer[offset] = exchange_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += exchange_len; + val = fields.routingKey; + void 0 === val && (val = void 0); + buffer[offset] = routingKey_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += routingKey_len; + val = fields.messageCount; + if (void 0 === val) throw new Error("Missing value for mandatory field 'messageCount'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)"); + buffer.writeUInt32BE(val, offset); + offset += 4; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicGetEmpty(buffer) { + var val, len, offset = 0, fields = { + clusterId: void 0 + }; + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.clusterId = val; + return fields; +} + +function encodeBasicGetEmpty(channel, fields) { + var offset = 0, val = null, varyingSize = 0; + val = fields.clusterId; + if (void 0 === val) val = ""; else if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); + var clusterId_len = Buffer.byteLength(val, "utf8"); + varyingSize += clusterId_len; + var buffer = Buffer.alloc(13 + varyingSize); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932232, 7); + offset = 11; + val = fields.clusterId; + void 0 === val && (val = ""); + buffer[offset] = clusterId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += clusterId_len; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicAck(buffer) { + var val, offset = 0, fields = { + deliveryTag: void 0, + multiple: void 0 + }; + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.deliveryTag = val; + val = !!(1 & buffer[offset]); + fields.multiple = val; + return fields; +} + +function encodeBasicAck(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932240, 7); + offset = 11; + val = fields.deliveryTag; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + val = fields.multiple; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicReject(buffer) { + var val, offset = 0, fields = { + deliveryTag: void 0, + requeue: void 0 + }; + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.deliveryTag = val; + val = !!(1 & buffer[offset]); + fields.requeue = val; + return fields; +} + +function encodeBasicReject(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932250, 7); + offset = 11; + val = fields.deliveryTag; + if (void 0 === val) throw new Error("Missing value for mandatory field 'deliveryTag'"); + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + val = fields.requeue; + void 0 === val && (val = !0); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicRecoverAsync(buffer) { + var val, fields = { + requeue: void 0 + }; + val = !!(1 & buffer[0]); + fields.requeue = val; + return fields; +} + +function encodeBasicRecoverAsync(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932260, 7); + offset = 11; + val = fields.requeue; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicRecover(buffer) { + var val, fields = { + requeue: void 0 + }; + val = !!(1 & buffer[0]); + fields.requeue = val; + return fields; +} + +function encodeBasicRecover(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932270, 7); + offset = 11; + val = fields.requeue; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicRecoverOk(buffer) { + return {}; +} + +function encodeBasicRecoverOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932271, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeBasicNack(buffer) { + var val, offset = 0, fields = { + deliveryTag: void 0, + multiple: void 0, + requeue: void 0 + }; + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.deliveryTag = val; + val = !!(1 & buffer[offset]); + fields.multiple = val; + val = !!(2 & buffer[offset]); + fields.requeue = val; + return fields; +} + +function encodeBasicNack(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(21); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932280, 7); + offset = 11; + val = fields.deliveryTag; + if (void 0 === val) val = 0; else if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)"); + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + val = fields.multiple; + void 0 === val && (val = !1); + val && (bits += 1); + val = fields.requeue; + void 0 === val && (val = !0); + val && (bits += 2); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxSelect(buffer) { + return {}; +} + +function encodeTxSelect(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898250, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxSelectOk(buffer) { + return {}; +} + +function encodeTxSelectOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898251, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxCommit(buffer) { + return {}; +} + +function encodeTxCommit(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898260, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxCommitOk(buffer) { + return {}; +} + +function encodeTxCommitOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898261, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxRollback(buffer) { + return {}; +} + +function encodeTxRollback(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898270, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeTxRollbackOk(buffer) { + return {}; +} + +function encodeTxRollbackOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5898271, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConfirmSelect(buffer) { + var val, fields = { + nowait: void 0 + }; + val = !!(1 & buffer[0]); + fields.nowait = val; + return fields; +} + +function encodeConfirmSelect(channel, fields) { + var offset = 0, val = null, bits = 0, buffer = Buffer.alloc(13); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5570570, 7); + offset = 11; + val = fields.nowait; + void 0 === val && (val = !1); + val && (bits += 1); + buffer[offset] = bits; + offset++; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function decodeConfirmSelectOk(buffer) { + return {}; +} + +function encodeConfirmSelectOk(channel, fields) { + var offset = 0, buffer = Buffer.alloc(12); + buffer[0] = 1; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(5570571, 7); + offset = 11; + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + return buffer; +} + +function encodeBasicProperties(channel, size, fields) { + var val, len, offset = 0, flags = 0, scratchOffset = 0, varyingSize = 0; + val = fields.contentType; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'contentType' is the wrong type; must be a string (up to 255 chars)"); + var contentType_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += contentType_len; + } + val = fields.contentEncoding; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'contentEncoding' is the wrong type; must be a string (up to 255 chars)"); + var contentEncoding_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += contentEncoding_len; + } + val = fields.headers; + if (void 0 != val) { + if ("object" != typeof val) throw new TypeError("Field 'headers' is the wrong type; must be an object"); + len = encodeTable(SCRATCH, val, scratchOffset); + var headers_encoded = SCRATCH.slice(scratchOffset, scratchOffset + len); + scratchOffset += len; + varyingSize += headers_encoded.length; + } + val = fields.deliveryMode; + if (void 0 != val) { + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'deliveryMode' is the wrong type; must be a number (but not NaN)"); + varyingSize += 1; + } + val = fields.priority; + if (void 0 != val) { + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'priority' is the wrong type; must be a number (but not NaN)"); + varyingSize += 1; + } + val = fields.correlationId; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'correlationId' is the wrong type; must be a string (up to 255 chars)"); + var correlationId_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += correlationId_len; + } + val = fields.replyTo; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'replyTo' is the wrong type; must be a string (up to 255 chars)"); + var replyTo_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += replyTo_len; + } + val = fields.expiration; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'expiration' is the wrong type; must be a string (up to 255 chars)"); + var expiration_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += expiration_len; + } + val = fields.messageId; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'messageId' is the wrong type; must be a string (up to 255 chars)"); + var messageId_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += messageId_len; + } + val = fields.timestamp; + if (void 0 != val) { + if ("number" != typeof val || isNaN(val)) throw new TypeError("Field 'timestamp' is the wrong type; must be a number (but not NaN)"); + varyingSize += 8; + } + val = fields.type; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)"); + var type_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += type_len; + } + val = fields.userId; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'userId' is the wrong type; must be a string (up to 255 chars)"); + var userId_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += userId_len; + } + val = fields.appId; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'appId' is the wrong type; must be a string (up to 255 chars)"); + var appId_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += appId_len; + } + val = fields.clusterId; + if (void 0 != val) { + if (!("string" == typeof val && Buffer.byteLength(val) < 256)) throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)"); + var clusterId_len = Buffer.byteLength(val, "utf8"); + varyingSize += 1; + varyingSize += clusterId_len; + } + var buffer = Buffer.alloc(22 + varyingSize); + buffer[0] = 2; + buffer.writeUInt16BE(channel, 1); + buffer.writeUInt32BE(3932160, 7); + ints.writeUInt64BE(buffer, size, 11); + flags = 0; + offset = 21; + val = fields.contentType; + if (void 0 != val) { + flags += 32768; + buffer[offset] = contentType_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += contentType_len; + } + val = fields.contentEncoding; + if (void 0 != val) { + flags += 16384; + buffer[offset] = contentEncoding_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += contentEncoding_len; + } + val = fields.headers; + if (void 0 != val) { + flags += 8192; + offset += headers_encoded.copy(buffer, offset); + } + val = fields.deliveryMode; + if (void 0 != val) { + flags += 4096; + buffer.writeUInt8(val, offset); + offset++; + } + val = fields.priority; + if (void 0 != val) { + flags += 2048; + buffer.writeUInt8(val, offset); + offset++; + } + val = fields.correlationId; + if (void 0 != val) { + flags += 1024; + buffer[offset] = correlationId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += correlationId_len; + } + val = fields.replyTo; + if (void 0 != val) { + flags += 512; + buffer[offset] = replyTo_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += replyTo_len; + } + val = fields.expiration; + if (void 0 != val) { + flags += 256; + buffer[offset] = expiration_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += expiration_len; + } + val = fields.messageId; + if (void 0 != val) { + flags += 128; + buffer[offset] = messageId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += messageId_len; + } + val = fields.timestamp; + if (void 0 != val) { + flags += 64; + ints.writeUInt64BE(buffer, val, offset); + offset += 8; + } + val = fields.type; + if (void 0 != val) { + flags += 32; + buffer[offset] = type_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += type_len; + } + val = fields.userId; + if (void 0 != val) { + flags += 16; + buffer[offset] = userId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += userId_len; + } + val = fields.appId; + if (void 0 != val) { + flags += 8; + buffer[offset] = appId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += appId_len; + } + val = fields.clusterId; + if (void 0 != val) { + flags += 4; + buffer[offset] = clusterId_len; + offset++; + buffer.write(val, offset, "utf8"); + offset += clusterId_len; + } + buffer[offset] = 206; + buffer.writeUInt32BE(offset - 7, 3); + buffer.writeUInt16BE(flags, 19); + return buffer.slice(0, offset + 1); +} + +function decodeBasicProperties(buffer) { + var flags, val, len, offset = 2; + flags = buffer.readUInt16BE(0); + if (0 === flags) return {}; + var fields = { + contentType: void 0, + contentEncoding: void 0, + headers: void 0, + deliveryMode: void 0, + priority: void 0, + correlationId: void 0, + replyTo: void 0, + expiration: void 0, + messageId: void 0, + timestamp: void 0, + type: void 0, + userId: void 0, + appId: void 0, + clusterId: void 0 + }; + if (32768 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.contentType = val; + } + if (16384 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.contentEncoding = val; + } + if (8192 & flags) { + len = buffer.readUInt32BE(offset); + offset += 4; + val = decodeFields(buffer.slice(offset, offset + len)); + offset += len; + fields.headers = val; + } + if (4096 & flags) { + val = buffer[offset]; + offset++; + fields.deliveryMode = val; + } + if (2048 & flags) { + val = buffer[offset]; + offset++; + fields.priority = val; + } + if (1024 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.correlationId = val; + } + if (512 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.replyTo = val; + } + if (256 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.expiration = val; + } + if (128 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.messageId = val; + } + if (64 & flags) { + val = ints.readUInt64BE(buffer, offset); + offset += 8; + fields.timestamp = val; + } + if (32 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.type = val; + } + if (16 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.userId = val; + } + if (8 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.appId = val; + } + if (4 & flags) { + len = buffer.readUInt8(offset); + offset++; + val = buffer.toString("utf8", offset, offset + len); + offset += len; + fields.clusterId = val; + } + return fields; +} + +var Buffer = require("safe-buffer").Buffer, codec = require("./codec"), ints = require("buffer-more-ints"), encodeTable = codec.encodeTable, decodeFields = codec.decodeFields, SCRATCH = Buffer.alloc(65536), EMPTY_OBJECT = Object.freeze({}); + +module.exports.constants = { + FRAME_METHOD: 1, + FRAME_HEADER: 2, + FRAME_BODY: 3, + FRAME_HEARTBEAT: 8, + FRAME_MIN_SIZE: 4096, + FRAME_END: 206, + REPLY_SUCCESS: 200, + CONTENT_TOO_LARGE: 311, + NO_ROUTE: 312, + NO_CONSUMERS: 313, + ACCESS_REFUSED: 403, + NOT_FOUND: 404, + RESOURCE_LOCKED: 405, + PRECONDITION_FAILED: 406, + CONNECTION_FORCED: 320, + INVALID_PATH: 402, + FRAME_ERROR: 501, + SYNTAX_ERROR: 502, + COMMAND_INVALID: 503, + CHANNEL_ERROR: 504, + UNEXPECTED_FRAME: 505, + RESOURCE_ERROR: 506, + NOT_ALLOWED: 530, + NOT_IMPLEMENTED: 540, + INTERNAL_ERROR: 541 +}; + +module.exports.constant_strs = { + "1": "FRAME-METHOD", + "2": "FRAME-HEADER", + "3": "FRAME-BODY", + "8": "FRAME-HEARTBEAT", + "200": "REPLY-SUCCESS", + "206": "FRAME-END", + "311": "CONTENT-TOO-LARGE", + "312": "NO-ROUTE", + "313": "NO-CONSUMERS", + "320": "CONNECTION-FORCED", + "402": "INVALID-PATH", + "403": "ACCESS-REFUSED", + "404": "NOT-FOUND", + "405": "RESOURCE-LOCKED", + "406": "PRECONDITION-FAILED", + "501": "FRAME-ERROR", + "502": "SYNTAX-ERROR", + "503": "COMMAND-INVALID", + "504": "CHANNEL-ERROR", + "505": "UNEXPECTED-FRAME", + "506": "RESOURCE-ERROR", + "530": "NOT-ALLOWED", + "540": "NOT-IMPLEMENTED", + "541": "INTERNAL-ERROR", + "4096": "FRAME-MIN-SIZE" +}; + +module.exports.FRAME_OVERHEAD = 8; + +module.exports.decode = function(id, buf) { + switch (id) { + case 655370: + return decodeConnectionStart(buf); + + case 655371: + return decodeConnectionStartOk(buf); + + case 655380: + return decodeConnectionSecure(buf); + + case 655381: + return decodeConnectionSecureOk(buf); + + case 655390: + return decodeConnectionTune(buf); + + case 655391: + return decodeConnectionTuneOk(buf); + + case 655400: + return decodeConnectionOpen(buf); + + case 655401: + return decodeConnectionOpenOk(buf); + + case 655410: + return decodeConnectionClose(buf); + + case 655411: + return decodeConnectionCloseOk(buf); + + case 655420: + return decodeConnectionBlocked(buf); + + case 655421: + return decodeConnectionUnblocked(buf); + + case 1310730: + return decodeChannelOpen(buf); + + case 1310731: + return decodeChannelOpenOk(buf); + + case 1310740: + return decodeChannelFlow(buf); + + case 1310741: + return decodeChannelFlowOk(buf); + + case 1310760: + return decodeChannelClose(buf); + + case 1310761: + return decodeChannelCloseOk(buf); + + case 1966090: + return decodeAccessRequest(buf); + + case 1966091: + return decodeAccessRequestOk(buf); + + case 2621450: + return decodeExchangeDeclare(buf); + + case 2621451: + return decodeExchangeDeclareOk(buf); + + case 2621460: + return decodeExchangeDelete(buf); + + case 2621461: + return decodeExchangeDeleteOk(buf); + + case 2621470: + return decodeExchangeBind(buf); + + case 2621471: + return decodeExchangeBindOk(buf); + + case 2621480: + return decodeExchangeUnbind(buf); + + case 2621491: + return decodeExchangeUnbindOk(buf); + + case 3276810: + return decodeQueueDeclare(buf); + + case 3276811: + return decodeQueueDeclareOk(buf); + + case 3276820: + return decodeQueueBind(buf); + + case 3276821: + return decodeQueueBindOk(buf); + + case 3276830: + return decodeQueuePurge(buf); + + case 3276831: + return decodeQueuePurgeOk(buf); + + case 3276840: + return decodeQueueDelete(buf); + + case 3276841: + return decodeQueueDeleteOk(buf); + + case 3276850: + return decodeQueueUnbind(buf); + + case 3276851: + return decodeQueueUnbindOk(buf); + + case 3932170: + return decodeBasicQos(buf); + + case 3932171: + return decodeBasicQosOk(buf); + + case 3932180: + return decodeBasicConsume(buf); + + case 3932181: + return decodeBasicConsumeOk(buf); + + case 3932190: + return decodeBasicCancel(buf); + + case 3932191: + return decodeBasicCancelOk(buf); + + case 3932200: + return decodeBasicPublish(buf); + + case 3932210: + return decodeBasicReturn(buf); + + case 3932220: + return decodeBasicDeliver(buf); + + case 3932230: + return decodeBasicGet(buf); + + case 3932231: + return decodeBasicGetOk(buf); + + case 3932232: + return decodeBasicGetEmpty(buf); + + case 3932240: + return decodeBasicAck(buf); + + case 3932250: + return decodeBasicReject(buf); + + case 3932260: + return decodeBasicRecoverAsync(buf); + + case 3932270: + return decodeBasicRecover(buf); + + case 3932271: + return decodeBasicRecoverOk(buf); + + case 3932280: + return decodeBasicNack(buf); + + case 5898250: + return decodeTxSelect(buf); + + case 5898251: + return decodeTxSelectOk(buf); + + case 5898260: + return decodeTxCommit(buf); + + case 5898261: + return decodeTxCommitOk(buf); + + case 5898270: + return decodeTxRollback(buf); + + case 5898271: + return decodeTxRollbackOk(buf); + + case 5570570: + return decodeConfirmSelect(buf); + + case 5570571: + return decodeConfirmSelectOk(buf); + + case 60: + return decodeBasicProperties(buf); + + default: + throw new Error("Unknown class/method ID"); + } +}; + +module.exports.encodeMethod = function(id, channel, fields) { + switch (id) { + case 655370: + return encodeConnectionStart(channel, fields); + + case 655371: + return encodeConnectionStartOk(channel, fields); + + case 655380: + return encodeConnectionSecure(channel, fields); + + case 655381: + return encodeConnectionSecureOk(channel, fields); + + case 655390: + return encodeConnectionTune(channel, fields); + + case 655391: + return encodeConnectionTuneOk(channel, fields); + + case 655400: + return encodeConnectionOpen(channel, fields); + + case 655401: + return encodeConnectionOpenOk(channel, fields); + + case 655410: + return encodeConnectionClose(channel, fields); + + case 655411: + return encodeConnectionCloseOk(channel, fields); + + case 655420: + return encodeConnectionBlocked(channel, fields); + + case 655421: + return encodeConnectionUnblocked(channel, fields); + + case 1310730: + return encodeChannelOpen(channel, fields); + + case 1310731: + return encodeChannelOpenOk(channel, fields); + + case 1310740: + return encodeChannelFlow(channel, fields); + + case 1310741: + return encodeChannelFlowOk(channel, fields); + + case 1310760: + return encodeChannelClose(channel, fields); + + case 1310761: + return encodeChannelCloseOk(channel, fields); + + case 1966090: + return encodeAccessRequest(channel, fields); + + case 1966091: + return encodeAccessRequestOk(channel, fields); + + case 2621450: + return encodeExchangeDeclare(channel, fields); + + case 2621451: + return encodeExchangeDeclareOk(channel, fields); + + case 2621460: + return encodeExchangeDelete(channel, fields); + + case 2621461: + return encodeExchangeDeleteOk(channel, fields); + + case 2621470: + return encodeExchangeBind(channel, fields); + + case 2621471: + return encodeExchangeBindOk(channel, fields); + + case 2621480: + return encodeExchangeUnbind(channel, fields); + + case 2621491: + return encodeExchangeUnbindOk(channel, fields); + + case 3276810: + return encodeQueueDeclare(channel, fields); + + case 3276811: + return encodeQueueDeclareOk(channel, fields); + + case 3276820: + return encodeQueueBind(channel, fields); + + case 3276821: + return encodeQueueBindOk(channel, fields); + + case 3276830: + return encodeQueuePurge(channel, fields); + + case 3276831: + return encodeQueuePurgeOk(channel, fields); + + case 3276840: + return encodeQueueDelete(channel, fields); + + case 3276841: + return encodeQueueDeleteOk(channel, fields); + + case 3276850: + return encodeQueueUnbind(channel, fields); + + case 3276851: + return encodeQueueUnbindOk(channel, fields); + + case 3932170: + return encodeBasicQos(channel, fields); + + case 3932171: + return encodeBasicQosOk(channel, fields); + + case 3932180: + return encodeBasicConsume(channel, fields); + + case 3932181: + return encodeBasicConsumeOk(channel, fields); + + case 3932190: + return encodeBasicCancel(channel, fields); + + case 3932191: + return encodeBasicCancelOk(channel, fields); + + case 3932200: + return encodeBasicPublish(channel, fields); + + case 3932210: + return encodeBasicReturn(channel, fields); + + case 3932220: + return encodeBasicDeliver(channel, fields); + + case 3932230: + return encodeBasicGet(channel, fields); + + case 3932231: + return encodeBasicGetOk(channel, fields); + + case 3932232: + return encodeBasicGetEmpty(channel, fields); + + case 3932240: + return encodeBasicAck(channel, fields); + + case 3932250: + return encodeBasicReject(channel, fields); + + case 3932260: + return encodeBasicRecoverAsync(channel, fields); + + case 3932270: + return encodeBasicRecover(channel, fields); + + case 3932271: + return encodeBasicRecoverOk(channel, fields); + + case 3932280: + return encodeBasicNack(channel, fields); + + case 5898250: + return encodeTxSelect(channel, fields); + + case 5898251: + return encodeTxSelectOk(channel, fields); + + case 5898260: + return encodeTxCommit(channel, fields); + + case 5898261: + return encodeTxCommitOk(channel, fields); + + case 5898270: + return encodeTxRollback(channel, fields); + + case 5898271: + return encodeTxRollbackOk(channel, fields); + + case 5570570: + return encodeConfirmSelect(channel, fields); + + case 5570571: + return encodeConfirmSelectOk(channel, fields); + + default: + throw new Error("Unknown class/method ID"); + } +}; + +module.exports.encodeProperties = function(id, channel, size, fields) { + switch (id) { + case 60: + return encodeBasicProperties(channel, size, fields); + + default: + throw new Error("Unknown class/properties ID"); + } +}; + +module.exports.info = function(id) { + switch (id) { + case 655370: + return methodInfoConnectionStart; + + case 655371: + return methodInfoConnectionStartOk; + + case 655380: + return methodInfoConnectionSecure; + + case 655381: + return methodInfoConnectionSecureOk; + + case 655390: + return methodInfoConnectionTune; + + case 655391: + return methodInfoConnectionTuneOk; + + case 655400: + return methodInfoConnectionOpen; + + case 655401: + return methodInfoConnectionOpenOk; + + case 655410: + return methodInfoConnectionClose; + + case 655411: + return methodInfoConnectionCloseOk; + + case 655420: + return methodInfoConnectionBlocked; + + case 655421: + return methodInfoConnectionUnblocked; + + case 1310730: + return methodInfoChannelOpen; + + case 1310731: + return methodInfoChannelOpenOk; + + case 1310740: + return methodInfoChannelFlow; + + case 1310741: + return methodInfoChannelFlowOk; + + case 1310760: + return methodInfoChannelClose; + + case 1310761: + return methodInfoChannelCloseOk; + + case 1966090: + return methodInfoAccessRequest; + + case 1966091: + return methodInfoAccessRequestOk; + + case 2621450: + return methodInfoExchangeDeclare; + + case 2621451: + return methodInfoExchangeDeclareOk; + + case 2621460: + return methodInfoExchangeDelete; + + case 2621461: + return methodInfoExchangeDeleteOk; + + case 2621470: + return methodInfoExchangeBind; + + case 2621471: + return methodInfoExchangeBindOk; + + case 2621480: + return methodInfoExchangeUnbind; + + case 2621491: + return methodInfoExchangeUnbindOk; + + case 3276810: + return methodInfoQueueDeclare; + + case 3276811: + return methodInfoQueueDeclareOk; + + case 3276820: + return methodInfoQueueBind; + + case 3276821: + return methodInfoQueueBindOk; + + case 3276830: + return methodInfoQueuePurge; + + case 3276831: + return methodInfoQueuePurgeOk; + + case 3276840: + return methodInfoQueueDelete; + + case 3276841: + return methodInfoQueueDeleteOk; + + case 3276850: + return methodInfoQueueUnbind; + + case 3276851: + return methodInfoQueueUnbindOk; + + case 3932170: + return methodInfoBasicQos; + + case 3932171: + return methodInfoBasicQosOk; + + case 3932180: + return methodInfoBasicConsume; + + case 3932181: + return methodInfoBasicConsumeOk; + + case 3932190: + return methodInfoBasicCancel; + + case 3932191: + return methodInfoBasicCancelOk; + + case 3932200: + return methodInfoBasicPublish; + + case 3932210: + return methodInfoBasicReturn; + + case 3932220: + return methodInfoBasicDeliver; + + case 3932230: + return methodInfoBasicGet; + + case 3932231: + return methodInfoBasicGetOk; + + case 3932232: + return methodInfoBasicGetEmpty; + + case 3932240: + return methodInfoBasicAck; + + case 3932250: + return methodInfoBasicReject; + + case 3932260: + return methodInfoBasicRecoverAsync; + + case 3932270: + return methodInfoBasicRecover; + + case 3932271: + return methodInfoBasicRecoverOk; + + case 3932280: + return methodInfoBasicNack; + + case 5898250: + return methodInfoTxSelect; + + case 5898251: + return methodInfoTxSelectOk; + + case 5898260: + return methodInfoTxCommit; + + case 5898261: + return methodInfoTxCommitOk; + + case 5898270: + return methodInfoTxRollback; + + case 5898271: + return methodInfoTxRollbackOk; + + case 5570570: + return methodInfoConfirmSelect; + + case 5570571: + return methodInfoConfirmSelectOk; + + case 60: + return propertiesInfoBasicProperties; + + default: + throw new Error("Unknown class/method ID"); + } +}; + +module.exports.ConnectionStart = 655370; + +var methodInfoConnectionStart = module.exports.methodInfoConnectionStart = { + id: 655370, + classId: 10, + methodId: 10, + name: "ConnectionStart", + args: [ { + type: "octet", + name: "versionMajor", + default: 0 + }, { + type: "octet", + name: "versionMinor", + default: 9 + }, { + type: "table", + name: "serverProperties" + }, { + type: "longstr", + name: "mechanisms", + default: "PLAIN" + }, { + type: "longstr", + name: "locales", + default: "en_US" + } ] +}; + +module.exports.ConnectionStartOk = 655371; + +var methodInfoConnectionStartOk = module.exports.methodInfoConnectionStartOk = { + id: 655371, + classId: 10, + methodId: 11, + name: "ConnectionStartOk", + args: [ { + type: "table", + name: "clientProperties" + }, { + type: "shortstr", + name: "mechanism", + default: "PLAIN" + }, { + type: "longstr", + name: "response" + }, { + type: "shortstr", + name: "locale", + default: "en_US" + } ] +}; + +module.exports.ConnectionSecure = 655380; + +var methodInfoConnectionSecure = module.exports.methodInfoConnectionSecure = { + id: 655380, + classId: 10, + methodId: 20, + name: "ConnectionSecure", + args: [ { + type: "longstr", + name: "challenge" + } ] +}; + +module.exports.ConnectionSecureOk = 655381; + +var methodInfoConnectionSecureOk = module.exports.methodInfoConnectionSecureOk = { + id: 655381, + classId: 10, + methodId: 21, + name: "ConnectionSecureOk", + args: [ { + type: "longstr", + name: "response" + } ] +}; + +module.exports.ConnectionTune = 655390; + +var methodInfoConnectionTune = module.exports.methodInfoConnectionTune = { + id: 655390, + classId: 10, + methodId: 30, + name: "ConnectionTune", + args: [ { + type: "short", + name: "channelMax", + default: 0 + }, { + type: "long", + name: "frameMax", + default: 0 + }, { + type: "short", + name: "heartbeat", + default: 0 + } ] +}; + +module.exports.ConnectionTuneOk = 655391; + +var methodInfoConnectionTuneOk = module.exports.methodInfoConnectionTuneOk = { + id: 655391, + classId: 10, + methodId: 31, + name: "ConnectionTuneOk", + args: [ { + type: "short", + name: "channelMax", + default: 0 + }, { + type: "long", + name: "frameMax", + default: 0 + }, { + type: "short", + name: "heartbeat", + default: 0 + } ] +}; + +module.exports.ConnectionOpen = 655400; + +var methodInfoConnectionOpen = module.exports.methodInfoConnectionOpen = { + id: 655400, + classId: 10, + methodId: 40, + name: "ConnectionOpen", + args: [ { + type: "shortstr", + name: "virtualHost", + default: "/" + }, { + type: "shortstr", + name: "capabilities", + default: "" + }, { + type: "bit", + name: "insist", + default: !1 + } ] +}; + +module.exports.ConnectionOpenOk = 655401; + +var methodInfoConnectionOpenOk = module.exports.methodInfoConnectionOpenOk = { + id: 655401, + classId: 10, + methodId: 41, + name: "ConnectionOpenOk", + args: [ { + type: "shortstr", + name: "knownHosts", + default: "" + } ] +}; + +module.exports.ConnectionClose = 655410; + +var methodInfoConnectionClose = module.exports.methodInfoConnectionClose = { + id: 655410, + classId: 10, + methodId: 50, + name: "ConnectionClose", + args: [ { + type: "short", + name: "replyCode" + }, { + type: "shortstr", + name: "replyText", + default: "" + }, { + type: "short", + name: "classId" + }, { + type: "short", + name: "methodId" + } ] +}; + +module.exports.ConnectionCloseOk = 655411; + +var methodInfoConnectionCloseOk = module.exports.methodInfoConnectionCloseOk = { + id: 655411, + classId: 10, + methodId: 51, + name: "ConnectionCloseOk", + args: [] +}; + +module.exports.ConnectionBlocked = 655420; + +var methodInfoConnectionBlocked = module.exports.methodInfoConnectionBlocked = { + id: 655420, + classId: 10, + methodId: 60, + name: "ConnectionBlocked", + args: [ { + type: "shortstr", + name: "reason", + default: "" + } ] +}; + +module.exports.ConnectionUnblocked = 655421; + +var methodInfoConnectionUnblocked = module.exports.methodInfoConnectionUnblocked = { + id: 655421, + classId: 10, + methodId: 61, + name: "ConnectionUnblocked", + args: [] +}; + +module.exports.ChannelOpen = 1310730; + +var methodInfoChannelOpen = module.exports.methodInfoChannelOpen = { + id: 1310730, + classId: 20, + methodId: 10, + name: "ChannelOpen", + args: [ { + type: "shortstr", + name: "outOfBand", + default: "" + } ] +}; + +module.exports.ChannelOpenOk = 1310731; + +var methodInfoChannelOpenOk = module.exports.methodInfoChannelOpenOk = { + id: 1310731, + classId: 20, + methodId: 11, + name: "ChannelOpenOk", + args: [ { + type: "longstr", + name: "channelId", + default: "" + } ] +}; + +module.exports.ChannelFlow = 1310740; + +var methodInfoChannelFlow = module.exports.methodInfoChannelFlow = { + id: 1310740, + classId: 20, + methodId: 20, + name: "ChannelFlow", + args: [ { + type: "bit", + name: "active" + } ] +}; + +module.exports.ChannelFlowOk = 1310741; + +var methodInfoChannelFlowOk = module.exports.methodInfoChannelFlowOk = { + id: 1310741, + classId: 20, + methodId: 21, + name: "ChannelFlowOk", + args: [ { + type: "bit", + name: "active" + } ] +}; + +module.exports.ChannelClose = 1310760; + +var methodInfoChannelClose = module.exports.methodInfoChannelClose = { + id: 1310760, + classId: 20, + methodId: 40, + name: "ChannelClose", + args: [ { + type: "short", + name: "replyCode" + }, { + type: "shortstr", + name: "replyText", + default: "" + }, { + type: "short", + name: "classId" + }, { + type: "short", + name: "methodId" + } ] +}; + +module.exports.ChannelCloseOk = 1310761; + +var methodInfoChannelCloseOk = module.exports.methodInfoChannelCloseOk = { + id: 1310761, + classId: 20, + methodId: 41, + name: "ChannelCloseOk", + args: [] +}; + +module.exports.AccessRequest = 1966090; + +var methodInfoAccessRequest = module.exports.methodInfoAccessRequest = { + id: 1966090, + classId: 30, + methodId: 10, + name: "AccessRequest", + args: [ { + type: "shortstr", + name: "realm", + default: "/data" + }, { + type: "bit", + name: "exclusive", + default: !1 + }, { + type: "bit", + name: "passive", + default: !0 + }, { + type: "bit", + name: "active", + default: !0 + }, { + type: "bit", + name: "write", + default: !0 + }, { + type: "bit", + name: "read", + default: !0 + } ] +}; + +module.exports.AccessRequestOk = 1966091; + +var methodInfoAccessRequestOk = module.exports.methodInfoAccessRequestOk = { + id: 1966091, + classId: 30, + methodId: 11, + name: "AccessRequestOk", + args: [ { + type: "short", + name: "ticket", + default: 1 + } ] +}; + +module.exports.ExchangeDeclare = 2621450; + +var methodInfoExchangeDeclare = module.exports.methodInfoExchangeDeclare = { + id: 2621450, + classId: 40, + methodId: 10, + name: "ExchangeDeclare", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "type", + default: "direct" + }, { + type: "bit", + name: "passive", + default: !1 + }, { + type: "bit", + name: "durable", + default: !1 + }, { + type: "bit", + name: "autoDelete", + default: !1 + }, { + type: "bit", + name: "internal", + default: !1 + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.ExchangeDeclareOk = 2621451; + +var methodInfoExchangeDeclareOk = module.exports.methodInfoExchangeDeclareOk = { + id: 2621451, + classId: 40, + methodId: 11, + name: "ExchangeDeclareOk", + args: [] +}; + +module.exports.ExchangeDelete = 2621460; + +var methodInfoExchangeDelete = module.exports.methodInfoExchangeDelete = { + id: 2621460, + classId: 40, + methodId: 20, + name: "ExchangeDelete", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "exchange" + }, { + type: "bit", + name: "ifUnused", + default: !1 + }, { + type: "bit", + name: "nowait", + default: !1 + } ] +}; + +module.exports.ExchangeDeleteOk = 2621461; + +var methodInfoExchangeDeleteOk = module.exports.methodInfoExchangeDeleteOk = { + id: 2621461, + classId: 40, + methodId: 21, + name: "ExchangeDeleteOk", + args: [] +}; + +module.exports.ExchangeBind = 2621470; + +var methodInfoExchangeBind = module.exports.methodInfoExchangeBind = { + id: 2621470, + classId: 40, + methodId: 30, + name: "ExchangeBind", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "destination" + }, { + type: "shortstr", + name: "source" + }, { + type: "shortstr", + name: "routingKey", + default: "" + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.ExchangeBindOk = 2621471; + +var methodInfoExchangeBindOk = module.exports.methodInfoExchangeBindOk = { + id: 2621471, + classId: 40, + methodId: 31, + name: "ExchangeBindOk", + args: [] +}; + +module.exports.ExchangeUnbind = 2621480; + +var methodInfoExchangeUnbind = module.exports.methodInfoExchangeUnbind = { + id: 2621480, + classId: 40, + methodId: 40, + name: "ExchangeUnbind", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "destination" + }, { + type: "shortstr", + name: "source" + }, { + type: "shortstr", + name: "routingKey", + default: "" + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.ExchangeUnbindOk = 2621491; + +var methodInfoExchangeUnbindOk = module.exports.methodInfoExchangeUnbindOk = { + id: 2621491, + classId: 40, + methodId: 51, + name: "ExchangeUnbindOk", + args: [] +}; + +module.exports.QueueDeclare = 3276810; + +var methodInfoQueueDeclare = module.exports.methodInfoQueueDeclare = { + id: 3276810, + classId: 50, + methodId: 10, + name: "QueueDeclare", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "bit", + name: "passive", + default: !1 + }, { + type: "bit", + name: "durable", + default: !1 + }, { + type: "bit", + name: "exclusive", + default: !1 + }, { + type: "bit", + name: "autoDelete", + default: !1 + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.QueueDeclareOk = 3276811; + +var methodInfoQueueDeclareOk = module.exports.methodInfoQueueDeclareOk = { + id: 3276811, + classId: 50, + methodId: 11, + name: "QueueDeclareOk", + args: [ { + type: "shortstr", + name: "queue" + }, { + type: "long", + name: "messageCount" + }, { + type: "long", + name: "consumerCount" + } ] +}; + +module.exports.QueueBind = 3276820; + +var methodInfoQueueBind = module.exports.methodInfoQueueBind = { + id: 3276820, + classId: 50, + methodId: 20, + name: "QueueBind", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "routingKey", + default: "" + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.QueueBindOk = 3276821; + +var methodInfoQueueBindOk = module.exports.methodInfoQueueBindOk = { + id: 3276821, + classId: 50, + methodId: 21, + name: "QueueBindOk", + args: [] +}; + +module.exports.QueuePurge = 3276830; + +var methodInfoQueuePurge = module.exports.methodInfoQueuePurge = { + id: 3276830, + classId: 50, + methodId: 30, + name: "QueuePurge", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "bit", + name: "nowait", + default: !1 + } ] +}; + +module.exports.QueuePurgeOk = 3276831; + +var methodInfoQueuePurgeOk = module.exports.methodInfoQueuePurgeOk = { + id: 3276831, + classId: 50, + methodId: 31, + name: "QueuePurgeOk", + args: [ { + type: "long", + name: "messageCount" + } ] +}; + +module.exports.QueueDelete = 3276840; + +var methodInfoQueueDelete = module.exports.methodInfoQueueDelete = { + id: 3276840, + classId: 50, + methodId: 40, + name: "QueueDelete", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "bit", + name: "ifUnused", + default: !1 + }, { + type: "bit", + name: "ifEmpty", + default: !1 + }, { + type: "bit", + name: "nowait", + default: !1 + } ] +}; + +module.exports.QueueDeleteOk = 3276841; + +var methodInfoQueueDeleteOk = module.exports.methodInfoQueueDeleteOk = { + id: 3276841, + classId: 50, + methodId: 41, + name: "QueueDeleteOk", + args: [ { + type: "long", + name: "messageCount" + } ] +}; + +module.exports.QueueUnbind = 3276850; + +var methodInfoQueueUnbind = module.exports.methodInfoQueueUnbind = { + id: 3276850, + classId: 50, + methodId: 50, + name: "QueueUnbind", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "routingKey", + default: "" + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.QueueUnbindOk = 3276851; + +var methodInfoQueueUnbindOk = module.exports.methodInfoQueueUnbindOk = { + id: 3276851, + classId: 50, + methodId: 51, + name: "QueueUnbindOk", + args: [] +}; + +module.exports.BasicQos = 3932170; + +var methodInfoBasicQos = module.exports.methodInfoBasicQos = { + id: 3932170, + classId: 60, + methodId: 10, + name: "BasicQos", + args: [ { + type: "long", + name: "prefetchSize", + default: 0 + }, { + type: "short", + name: "prefetchCount", + default: 0 + }, { + type: "bit", + name: "global", + default: !1 + } ] +}; + +module.exports.BasicQosOk = 3932171; + +var methodInfoBasicQosOk = module.exports.methodInfoBasicQosOk = { + id: 3932171, + classId: 60, + methodId: 11, + name: "BasicQosOk", + args: [] +}; + +module.exports.BasicConsume = 3932180; + +var methodInfoBasicConsume = module.exports.methodInfoBasicConsume = { + id: 3932180, + classId: 60, + methodId: 20, + name: "BasicConsume", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "shortstr", + name: "consumerTag", + default: "" + }, { + type: "bit", + name: "noLocal", + default: !1 + }, { + type: "bit", + name: "noAck", + default: !1 + }, { + type: "bit", + name: "exclusive", + default: !1 + }, { + type: "bit", + name: "nowait", + default: !1 + }, { + type: "table", + name: "arguments", + default: {} + } ] +}; + +module.exports.BasicConsumeOk = 3932181; + +var methodInfoBasicConsumeOk = module.exports.methodInfoBasicConsumeOk = { + id: 3932181, + classId: 60, + methodId: 21, + name: "BasicConsumeOk", + args: [ { + type: "shortstr", + name: "consumerTag" + } ] +}; + +module.exports.BasicCancel = 3932190; + +var methodInfoBasicCancel = module.exports.methodInfoBasicCancel = { + id: 3932190, + classId: 60, + methodId: 30, + name: "BasicCancel", + args: [ { + type: "shortstr", + name: "consumerTag" + }, { + type: "bit", + name: "nowait", + default: !1 + } ] +}; + +module.exports.BasicCancelOk = 3932191; + +var methodInfoBasicCancelOk = module.exports.methodInfoBasicCancelOk = { + id: 3932191, + classId: 60, + methodId: 31, + name: "BasicCancelOk", + args: [ { + type: "shortstr", + name: "consumerTag" + } ] +}; + +module.exports.BasicPublish = 3932200; + +var methodInfoBasicPublish = module.exports.methodInfoBasicPublish = { + id: 3932200, + classId: 60, + methodId: 40, + name: "BasicPublish", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "exchange", + default: "" + }, { + type: "shortstr", + name: "routingKey", + default: "" + }, { + type: "bit", + name: "mandatory", + default: !1 + }, { + type: "bit", + name: "immediate", + default: !1 + } ] +}; + +module.exports.BasicReturn = 3932210; + +var methodInfoBasicReturn = module.exports.methodInfoBasicReturn = { + id: 3932210, + classId: 60, + methodId: 50, + name: "BasicReturn", + args: [ { + type: "short", + name: "replyCode" + }, { + type: "shortstr", + name: "replyText", + default: "" + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "routingKey" + } ] +}; + +module.exports.BasicDeliver = 3932220; + +var methodInfoBasicDeliver = module.exports.methodInfoBasicDeliver = { + id: 3932220, + classId: 60, + methodId: 60, + name: "BasicDeliver", + args: [ { + type: "shortstr", + name: "consumerTag" + }, { + type: "longlong", + name: "deliveryTag" + }, { + type: "bit", + name: "redelivered", + default: !1 + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "routingKey" + } ] +}; + +module.exports.BasicGet = 3932230; + +var methodInfoBasicGet = module.exports.methodInfoBasicGet = { + id: 3932230, + classId: 60, + methodId: 70, + name: "BasicGet", + args: [ { + type: "short", + name: "ticket", + default: 0 + }, { + type: "shortstr", + name: "queue", + default: "" + }, { + type: "bit", + name: "noAck", + default: !1 + } ] +}; + +module.exports.BasicGetOk = 3932231; + +var methodInfoBasicGetOk = module.exports.methodInfoBasicGetOk = { + id: 3932231, + classId: 60, + methodId: 71, + name: "BasicGetOk", + args: [ { + type: "longlong", + name: "deliveryTag" + }, { + type: "bit", + name: "redelivered", + default: !1 + }, { + type: "shortstr", + name: "exchange" + }, { + type: "shortstr", + name: "routingKey" + }, { + type: "long", + name: "messageCount" + } ] +}; + +module.exports.BasicGetEmpty = 3932232; + +var methodInfoBasicGetEmpty = module.exports.methodInfoBasicGetEmpty = { + id: 3932232, + classId: 60, + methodId: 72, + name: "BasicGetEmpty", + args: [ { + type: "shortstr", + name: "clusterId", + default: "" + } ] +}; + +module.exports.BasicAck = 3932240; + +var methodInfoBasicAck = module.exports.methodInfoBasicAck = { + id: 3932240, + classId: 60, + methodId: 80, + name: "BasicAck", + args: [ { + type: "longlong", + name: "deliveryTag", + default: 0 + }, { + type: "bit", + name: "multiple", + default: !1 + } ] +}; + +module.exports.BasicReject = 3932250; + +var methodInfoBasicReject = module.exports.methodInfoBasicReject = { + id: 3932250, + classId: 60, + methodId: 90, + name: "BasicReject", + args: [ { + type: "longlong", + name: "deliveryTag" + }, { + type: "bit", + name: "requeue", + default: !0 + } ] +}; + +module.exports.BasicRecoverAsync = 3932260; + +var methodInfoBasicRecoverAsync = module.exports.methodInfoBasicRecoverAsync = { + id: 3932260, + classId: 60, + methodId: 100, + name: "BasicRecoverAsync", + args: [ { + type: "bit", + name: "requeue", + default: !1 + } ] +}; + +module.exports.BasicRecover = 3932270; + +var methodInfoBasicRecover = module.exports.methodInfoBasicRecover = { + id: 3932270, + classId: 60, + methodId: 110, + name: "BasicRecover", + args: [ { + type: "bit", + name: "requeue", + default: !1 + } ] +}; + +module.exports.BasicRecoverOk = 3932271; + +var methodInfoBasicRecoverOk = module.exports.methodInfoBasicRecoverOk = { + id: 3932271, + classId: 60, + methodId: 111, + name: "BasicRecoverOk", + args: [] +}; + +module.exports.BasicNack = 3932280; + +var methodInfoBasicNack = module.exports.methodInfoBasicNack = { + id: 3932280, + classId: 60, + methodId: 120, + name: "BasicNack", + args: [ { + type: "longlong", + name: "deliveryTag", + default: 0 + }, { + type: "bit", + name: "multiple", + default: !1 + }, { + type: "bit", + name: "requeue", + default: !0 + } ] +}; + +module.exports.TxSelect = 5898250; + +var methodInfoTxSelect = module.exports.methodInfoTxSelect = { + id: 5898250, + classId: 90, + methodId: 10, + name: "TxSelect", + args: [] +}; + +module.exports.TxSelectOk = 5898251; + +var methodInfoTxSelectOk = module.exports.methodInfoTxSelectOk = { + id: 5898251, + classId: 90, + methodId: 11, + name: "TxSelectOk", + args: [] +}; + +module.exports.TxCommit = 5898260; + +var methodInfoTxCommit = module.exports.methodInfoTxCommit = { + id: 5898260, + classId: 90, + methodId: 20, + name: "TxCommit", + args: [] +}; + +module.exports.TxCommitOk = 5898261; + +var methodInfoTxCommitOk = module.exports.methodInfoTxCommitOk = { + id: 5898261, + classId: 90, + methodId: 21, + name: "TxCommitOk", + args: [] +}; + +module.exports.TxRollback = 5898270; + +var methodInfoTxRollback = module.exports.methodInfoTxRollback = { + id: 5898270, + classId: 90, + methodId: 30, + name: "TxRollback", + args: [] +}; + +module.exports.TxRollbackOk = 5898271; + +var methodInfoTxRollbackOk = module.exports.methodInfoTxRollbackOk = { + id: 5898271, + classId: 90, + methodId: 31, + name: "TxRollbackOk", + args: [] +}; + +module.exports.ConfirmSelect = 5570570; + +var methodInfoConfirmSelect = module.exports.methodInfoConfirmSelect = { + id: 5570570, + classId: 85, + methodId: 10, + name: "ConfirmSelect", + args: [ { + type: "bit", + name: "nowait", + default: !1 + } ] +}; + +module.exports.ConfirmSelectOk = 5570571; + +var methodInfoConfirmSelectOk = module.exports.methodInfoConfirmSelectOk = { + id: 5570571, + classId: 85, + methodId: 11, + name: "ConfirmSelectOk", + args: [] +}; + +module.exports.BasicProperties = 60; + +var propertiesInfoBasicProperties = module.exports.propertiesInfoBasicProperties = { + id: 60, + name: "BasicProperties", + args: [ { + type: "shortstr", + name: "contentType" + }, { + type: "shortstr", + name: "contentEncoding" + }, { + type: "table", + name: "headers" + }, { + type: "octet", + name: "deliveryMode" + }, { + type: "octet", + name: "priority" + }, { + type: "shortstr", + name: "correlationId" + }, { + type: "shortstr", + name: "replyTo" + }, { + type: "shortstr", + name: "expiration" + }, { + type: "shortstr", + name: "messageId" + }, { + type: "timestamp", + name: "timestamp" + }, { + type: "shortstr", + name: "type" + }, { + type: "shortstr", + name: "userId" + }, { + type: "shortstr", + name: "appId" + }, { + type: "shortstr", + name: "clusterId" + } ] +}; \ No newline at end of file diff --git a/node_modules/amqplib/lib/error.js b/node_modules/amqplib/lib/error.js new file mode 100644 index 0000000..02c4903 --- /dev/null +++ b/node_modules/amqplib/lib/error.js @@ -0,0 +1,24 @@ +var inherits = require('util').inherits; + +function trimStack(stack, num) { + return stack && stack.split('\n').slice(num).join('\n'); +} + +function IllegalOperationError(msg, stack) { + var tmp = new Error(); + this.message = msg; + this.stack = this.toString() + '\n' + trimStack(tmp.stack, 2); + this.stackAtStateChange = stack; +} +inherits(IllegalOperationError, Error); + +IllegalOperationError.prototype.name = 'IllegalOperationError'; + +function stackCapture(reason) { + var e = new Error(); + return 'Stack capture: ' + reason + '\n' + + trimStack(e.stack, 2); +} + +module.exports.IllegalOperationError = IllegalOperationError; +module.exports.stackCapture = stackCapture; diff --git a/node_modules/amqplib/lib/format.js b/node_modules/amqplib/lib/format.js new file mode 100644 index 0000000..2966a6d --- /dev/null +++ b/node_modules/amqplib/lib/format.js @@ -0,0 +1,40 @@ +// +// +// + +// Stringifying various things + +'use strict'; + +var defs = require('./defs'); +var format = require('util').format; +var inherits = require('util').inherits; +var HEARTBEAT = require('./frame').HEARTBEAT; + +module.exports.closeMessage = function(close) { + var code = close.fields.replyCode; + return format('%d (%s) with message "%s"', + code, defs.constant_strs[code], + close.fields.replyText); +} + +module.exports.methodName = function(id) { + return defs.info(id).name; +}; + +module.exports.inspect = function(frame, showFields) { + if (frame === HEARTBEAT) { + return ''; + } + else if (!frame.id) { + return format('', + frame.channel, frame.size); + } + else { + var info = defs.info(frame.id); + return format('<%s channel:%d%s>', info.name, frame.channel, + (showFields) + ? ' ' + JSON.stringify(frame.fields, undefined, 2) + : ''); + } +} diff --git a/node_modules/amqplib/lib/frame.js b/node_modules/amqplib/lib/frame.js new file mode 100644 index 0000000..5ea86fa --- /dev/null +++ b/node_modules/amqplib/lib/frame.js @@ -0,0 +1,114 @@ +// The river sweeps through +// Silt and twigs, gravel and leaves +// Driving the wheel on + +'use strict'; + +var defs = require('./defs'); +var constants = defs.constants; +var decode = defs.decode; +var Buffer = require('safe-buffer').Buffer + +var Bits = require('bitsyntax'); + +module.exports.PROTOCOL_HEADER = "AMQP" + String.fromCharCode(0, 0, 9, 1); + +/* + Frame format: + + 0 1 3 7 size+7 size+8 + +------+---------+-------------+ +------------+ +-----------+ + | type | channel | size | | payload | | frame-end | + +------+---------+-------------+ +------------+ +-----------+ + octet short long size octets octet + + In general I want to know those first three things straight away, so I + can discard frames early. + +*/ + +// framing constants +var FRAME_METHOD = constants.FRAME_METHOD, +FRAME_HEARTBEAT = constants.FRAME_HEARTBEAT, +FRAME_HEADER = constants.FRAME_HEADER, +FRAME_BODY = constants.FRAME_BODY, +FRAME_END = constants.FRAME_END; + +var bodyCons = + Bits.builder(FRAME_BODY, + 'channel:16, size:32, payload:size/binary', + FRAME_END); + +// %%% TESTME possibly better to cons the first bit and write the +// second directly, in the absence of IO lists +module.exports.makeBodyFrame = function(channel, payload) { + return bodyCons({channel: channel, size: payload.length, payload: payload}); +}; + +var frameHeaderPattern = Bits.matcher('type:8', 'channel:16', + 'size:32', 'rest/binary'); + +function parseFrame(bin, max) { + var fh = frameHeaderPattern(bin); + if (fh) { + var size = fh.size, rest = fh.rest; + if (size > max) { + throw new Error('Frame size exceeds frame max'); + } + else if (rest.length > size) { + if (rest[size] !== FRAME_END) + throw new Error('Invalid frame'); + + return { + type: fh.type, + channel: fh.channel, + size: size, + payload: rest.slice(0, size), + rest: rest.slice(size + 1) + }; + } + } + return false; +} + +module.exports.parseFrame = parseFrame; + +var headerPattern = Bits.matcher('class:16', + '_weight:16', + 'size:64', + 'flagsAndfields/binary'); + +var methodPattern = Bits.matcher('id:32, args/binary'); + +var HEARTBEAT = {channel: 0}; + +module.exports.decodeFrame = function(frame) { + var payload = frame.payload; + switch (frame.type) { + case FRAME_METHOD: + var idAndArgs = methodPattern(payload); + var id = idAndArgs.id; + var fields = decode(id, idAndArgs.args); + return {id: id, channel: frame.channel, fields: fields}; + case FRAME_HEADER: + var parts = headerPattern(payload); + var id = parts['class']; + var fields = decode(id, parts.flagsAndfields); + return {id: id, channel: frame.channel, + size: parts.size, fields: fields}; + case FRAME_BODY: + return {channel: frame.channel, content: frame.payload}; + case FRAME_HEARTBEAT: + return HEARTBEAT; + default: + throw new Error('Unknown frame type ' + frame.type); + } +} + +// encoded heartbeat +module.exports.HEARTBEAT_BUF = Buffer.from([constants.FRAME_HEARTBEAT, + 0, 0, 0, 0, // size = 0 + 0, 0, // channel = 0 + constants.FRAME_END]); + +module.exports.HEARTBEAT = HEARTBEAT; diff --git a/node_modules/amqplib/lib/heartbeat.js b/node_modules/amqplib/lib/heartbeat.js new file mode 100644 index 0000000..a9c9fb2 --- /dev/null +++ b/node_modules/amqplib/lib/heartbeat.js @@ -0,0 +1,89 @@ +// +// +// + +// Heartbeats. In AMQP both clients and servers may expect a heartbeat +// frame if there is no activity on the connection for a negotiated +// period of time. If there's no activity for two such intervals, the +// server or client is allowed to close the connection on the +// presumption that the other party is dead. +// +// The client has two jobs here: the first is to send a heartbeat +// frame if it's not sent any frames for a while, so that the server +// doesn't think it's dead; the second is to check periodically that +// it's seen activity from the server, and to advise if there doesn't +// appear to have been any for over two intervals. +// +// Node.JS timers are a bit unreliable, in that they endeavour only to +// fire at some indeterminate point *after* the given time (rather +// gives the lie to 'realtime', dunnit). Because the scheduler is just +// an event loop, it's quite easy to delay timers indefinitely by +// reacting to some I/O with a lot of computation. +// +// To mitigate this I need a bit of creative interpretation: +// +// - I'll schedule a server activity check for every `interval`, and +// check just how much time has passed. It will overshoot by at +// least a small margin; modulo missing timer deadlines, it'll +// notice between two and three intervals after activity actually +// stops (otherwise, at some point after two intervals). +// +// - Every `interval / 2` I'll check that we've sent something since +// the last check, and if not, send a heartbeat frame. If we're +// really too busy to even run the check for two whole heartbeat +// intervals, there must be a lot of I (but not O, at least not on +// the connection), or computation, in which case perhaps it's best +// the server cuts us off anyway. Why `interval / 2`? Because the +// edge case is that the client sent a frame just after a +// heartbeat, which would mean I only send one after almost two +// intervals. (NB a heartbeat counts as a send, so it'll be checked +// at least twice before sending another) +// +// This design is based largely on RabbitMQ's heartbeating: +// https://github.com/rabbitmq/rabbitmq-common/blob/master/src/rabbit_heartbeat.erl + +// %% Yes, I could apply the same 'actually passage of time' thing to +// %% send as well as to recv. + +'use strict'; + +var inherits = require('util').inherits; +var EventEmitter = require('events').EventEmitter; + +// Exported so that we can mess with it in tests +module.exports.UNITS_TO_MS = 1000; + +function Heart(interval, checkSend, checkRecv) { + EventEmitter.call(this); + this.interval = interval; + + var intervalMs = interval * module.exports.UNITS_TO_MS; + // Function#bind is my new best friend + var beat = this.emit.bind(this, 'beat'); + var timeout = this.emit.bind(this, 'timeout'); + + this.sendTimer = setInterval( + this.runHeartbeat.bind(this, checkSend, beat), intervalMs / 2); + + // A timeout occurs if I see nothing for *two consecutive* intervals + var recvMissed = 0; + function missedTwo() { + if (!checkRecv()) return (++recvMissed < 2); + else { recvMissed = 0; return true; } + } + this.recvTimer = setInterval( + this.runHeartbeat.bind(this, missedTwo, timeout), intervalMs); +} +inherits(Heart, EventEmitter); + +module.exports.Heart = Heart; + +Heart.prototype.clear = function() { + clearInterval(this.sendTimer); + clearInterval(this.recvTimer); +}; + +Heart.prototype.runHeartbeat = function(check, fail) { + // Have we seen activity? + if (!check()) fail(); +}; diff --git a/node_modules/amqplib/lib/mux.js b/node_modules/amqplib/lib/mux.js new file mode 100644 index 0000000..09040d8 --- /dev/null +++ b/node_modules/amqplib/lib/mux.js @@ -0,0 +1,131 @@ +// +// +// + +'use strict'; + +// A Mux is an object into which other readable streams may be piped; +// it then writes 'packets' from the upstreams to the given +// downstream. + +var inherits = require('util').inherits; +var assert = require('assert'); + +var schedule = (typeof setImmediate === 'function') ? + setImmediate : process.nextTick; + +function Mux(downstream) { + this.newStreams = []; + this.oldStreams = []; + this.blocked = false; + this.scheduledRead = false; + + this.out = downstream; + var self = this; + downstream.on('drain', function() { + self.blocked = false; + self._readIncoming(); + }); +} + +// There are 2 states we can be in: + +// - waiting for outbound capacity, which will be signalled by a +// - 'drain' event on the downstream; or, + +// - no packets to send, waiting for an inbound buffer to have +// packets, which will be signalled by a 'readable' event + +// If we write all packets available whenever there is outbound +// capacity, we will either run out of outbound capacity (`#write` +// returns false), or run out of packets (all calls to an +// `inbound.read()` have returned null). + +Mux.prototype._readIncoming = function() { + + // We may be sent here speculatively, if an incoming stream has + // become readable + if (this.blocked) return; + + var self = this; + var accepting = true; + var out = this.out; + + // Try to read a chunk from each stream in turn, until all streams + // are empty, or we exhaust our ability to accept chunks. + function roundrobin(streams) { + var s; + while (accepting && (s = streams.shift())) { + var chunk = s.read(); + if (chunk !== null) { + accepting = out.write(chunk); + streams.push(s); + } + } + } + + roundrobin(this.newStreams); + + // Either we exhausted the new queues, or we ran out of capacity. If + // we ran out of capacity, all the remaining new streams (i.e., + // those with packets left) become old streams. This effectively + // prioritises streams that keep their buffers close to empty over + // those that are constantly near full. + + if (accepting) { // all new queues are exhausted, write as many as + // we can from the old streams + assert.equal(0, this.newStreams.length); + roundrobin(this.oldStreams); + } + else { // ran out of room + assert(this.newStreams.length > 0, "Expect some new streams to remain"); + this.oldStreams = this.oldStreams.concat(this.newStreams); + this.newStreams = []; + } + // We may have exhausted all the old queues, or run out of room; + // either way, all we need to do is record whether we have capacity + // or not, so any speculative reads will know + this.blocked = !accepting; +}; + +Mux.prototype._scheduleRead = function() { + var self = this; + + if (!self.scheduledRead) { + schedule(function() { + self.scheduledRead = false; + self._readIncoming(); + }); + self.scheduledRead = true; + } +}; + +Mux.prototype.pipeFrom = function(readable) { + var self = this; + + function enqueue() { + self.newStreams.push(readable); + self._scheduleRead(); + } + + function cleanup() { + readable.removeListener('readable', enqueue); + readable.removeListener('error', cleanup); + readable.removeListener('end', cleanup); + readable.removeListener('unpipeFrom', cleanupIfMe); + } + function cleanupIfMe(dest) { + if (dest === self) cleanup(); + } + + readable.on('unpipeFrom', cleanupIfMe); + readable.on('end', cleanup); + readable.on('error', cleanup); + readable.on('readable', enqueue); +}; + +Mux.prototype.unpipeFrom = function(readable) { + readable.emit('unpipeFrom', this); +}; + +module.exports.Mux = Mux; diff --git a/node_modules/amqplib/package-lock.json b/node_modules/amqplib/package-lock.json new file mode 100644 index 0000000..80cfa27 --- /dev/null +++ b/node_modules/amqplib/package-lock.json @@ -0,0 +1,1623 @@ +{ + "name": "amqplib", + "version": "0.8.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "amqplib", + "version": "0.7.1", + "license": "MIT", + "dependencies": { + "bitsyntax": "~0.1.0", + "bluebird": "^3.7.2", + "buffer-more-ints": "~1.0.0", + "readable-stream": "1.x >=1.1.9", + "safe-buffer": "~5.2.1", + "url-parse": "~1.5.1" + }, + "devDependencies": { + "claire": "0.4.1", + "istanbul": "0.1.x", + "mocha": "^3.5.3", + "uglify-js": "2.8.x" + }, + "engines": { + "node": ">=0.8 <=15" + } + }, + "node_modules/abbrev": { + "version": "1.0.9", + "resolved": "http://npm.tescloud.com/abbrev/-/abbrev-1.0.9.tgz", + "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", + "dev": true + }, + "node_modules/align-text": { + "version": "0.1.4", + "resolved": "http://npm.tescloud.com/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", + "dev": true, + "dependencies": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/amdefine": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true, + "engines": { + "node": ">=0.4.2" + } + }, + "node_modules/async": { + "version": "0.2.10", + "resolved": "http://npm.tescloud.com/async/-/async-0.2.10.tgz", + "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=", + "dev": true + }, + "node_modules/balanced-match": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "node_modules/bitsyntax": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.1.0.tgz", + "integrity": "sha512-ikAdCnrloKmFOugAfxWws89/fPc+nw0OOG1IzIE72uSOg/A3cYptKCjSUhDTuj7fhsJtzkzlv7l3b8PzRHLN0Q==", + "dependencies": { + "buffer-more-ints": "~1.0.0", + "debug": "~2.6.9", + "safe-buffer": "~5.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/bitsyntax/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/bitsyntax/node_modules/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==" + }, + "node_modules/bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + }, + "node_modules/boo": { + "version": "1.2.4", + "resolved": "http://npm.tescloud.com/boo/-/boo-1.2.4.tgz", + "integrity": "sha1-szMxw2xK552C9P0ORJBgTLfFE7U=", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "http://npm.tescloud.com/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/browser-stdout": { + "version": "1.3.0", + "resolved": "http://npm.tescloud.com/browser-stdout/-/browser-stdout-1.3.0.tgz", + "integrity": "sha1-81HTKWnTL6XXpVZxVCY9korjvR8=", + "dev": true + }, + "node_modules/buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==" + }, + "node_modules/camelcase": { + "version": "1.2.1", + "resolved": "http://npm.tescloud.com/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/center-align": { + "version": "0.1.3", + "resolved": "http://npm.tescloud.com/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", + "dev": true, + "dependencies": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/claire": { + "version": "0.4.1", + "resolved": "http://npm.tescloud.com/claire/-/claire-0.4.1.tgz", + "integrity": "sha1-ynDcEmHd2PJaGvq604BcOfziY7w=", + "dev": true, + "dependencies": { + "boo": "~1.2.4", + "flaw": "~0.1.0", + "prelude-ls": "~0.6.0" + } + }, + "node_modules/cliui": { + "version": "2.1.0", + "resolved": "http://npm.tescloud.com/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", + "dev": true, + "dependencies": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + } + }, + "node_modules/cliui/node_modules/wordwrap": { + "version": "0.0.2", + "resolved": "http://npm.tescloud.com/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/commander": { + "version": "2.9.0", + "resolved": "http://npm.tescloud.com/commander/-/commander-2.9.0.tgz", + "integrity": "sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q=", + "dev": true, + "dependencies": { + "graceful-readlink": ">= 1.0.0" + }, + "engines": { + "node": ">= 0.6.x" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "http://npm.tescloud.com/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "node_modules/debug": { + "version": "2.6.8", + "resolved": "http://npm.tescloud.com/debug/-/debug-2.6.8.tgz", + "integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw=", + "dev": true, + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "http://npm.tescloud.com/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/diff": { + "version": "3.2.0", + "resolved": "http://npm.tescloud.com/diff/-/diff-3.2.0.tgz", + "integrity": "sha1-yc45Okt8vQsFinJck98pkCeGj/k=", + "dev": true, + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "http://npm.tescloud.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/escodegen": { + "version": "0.0.23", + "resolved": "http://npm.tescloud.com/escodegen/-/escodegen-0.0.23.tgz", + "integrity": "sha1-ms+XgWQ2jkInZXHxiDnII7OoRN8=", + "dev": true, + "dependencies": { + "esprima": "~1.0.2", + "estraverse": "~0.0.4", + "source-map": ">= 0.1.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=0.4.0" + }, + "optionalDependencies": { + "source-map": ">= 0.1.2" + } + }, + "node_modules/esprima": { + "version": "1.0.4", + "resolved": "http://npm.tescloud.com/esprima/-/esprima-1.0.4.tgz", + "integrity": "sha1-n1V+CPw7TSbs6d00+Pv0drYlha0=", + "dev": true, + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/estraverse": { + "version": "0.0.4", + "resolved": "http://npm.tescloud.com/estraverse/-/estraverse-0.0.4.tgz", + "integrity": "sha1-AaCTLf7ldGhKWYr1pnw7+bZCjbI=", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/fileset": { + "version": "0.1.8", + "resolved": "http://npm.tescloud.com/fileset/-/fileset-0.1.8.tgz", + "integrity": "sha1-UGuRqTluqn4y+0KoQHfHoMc2t0E=", + "dev": true, + "dependencies": { + "glob": "3.x", + "minimatch": "0.x" + } + }, + "node_modules/flaw": { + "version": "0.1.0", + "resolved": "http://npm.tescloud.com/flaw/-/flaw-0.1.0.tgz", + "integrity": "sha1-wMPo+BYWdTh+2tofbOhNZ5sCUn8=", + "dev": true + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "node_modules/glob": { + "version": "3.2.11", + "resolved": "http://npm.tescloud.com/glob/-/glob-3.2.11.tgz", + "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", + "dev": true, + "dependencies": { + "inherits": "2", + "minimatch": "0.3" + }, + "engines": { + "node": "*" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "0.3.0", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-0.3.0.tgz", + "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", + "dev": true, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/graceful-readlink": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz", + "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU=", + "dev": true + }, + "node_modules/growl": { + "version": "1.9.2", + "resolved": "http://npm.tescloud.com/growl/-/growl-1.9.2.tgz", + "integrity": "sha1-Dqd0NxXbjY3ixe3hd14bRayFwC8=", + "dev": true + }, + "node_modules/handlebars": { + "version": "1.0.12", + "resolved": "http://npm.tescloud.com/handlebars/-/handlebars-1.0.12.tgz", + "integrity": "sha1-GMbTRAw16RsZs/9YK5FRq0mF1Pw=", + "dev": true, + "dependencies": { + "optimist": "~0.3", + "uglify-js": "~2.3" + }, + "bin": { + "handlebars": "bin/handlebars" + }, + "engines": { + "node": ">=0.4.7" + } + }, + "node_modules/handlebars/node_modules/source-map": { + "version": "0.1.43", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.1.43.tgz", + "integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=", + "dev": true, + "dependencies": { + "amdefine": ">=0.0.4" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/handlebars/node_modules/uglify-js": { + "version": "2.3.6", + "resolved": "http://npm.tescloud.com/uglify-js/-/uglify-js-2.3.6.tgz", + "integrity": "sha1-+gmEdwtCi3qbKoBY9GNV0U/vIRo=", + "dev": true, + "dependencies": { + "async": "~0.2.6", + "optimist": "~0.3.5", + "source-map": "~0.1.7" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/has-flag": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/he": { + "version": "1.1.1", + "resolved": "http://npm.tescloud.com/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true, + "bin": { + "he": "bin/he" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "http://npm.tescloud.com/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.3", + "resolved": "http://npm.tescloud.com/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "http://npm.tescloud.com/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "node_modules/isarray": { + "version": "0.0.1", + "resolved": "http://npm.tescloud.com/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "node_modules/istanbul": { + "version": "0.1.46", + "resolved": "http://npm.tescloud.com/istanbul/-/istanbul-0.1.46.tgz", + "integrity": "sha1-zv6xx4fRJabbI70PY7Drk5CwtA0=", + "dev": true, + "dependencies": { + "abbrev": "1.0.x", + "async": "0.2.x", + "escodegen": "0.0.23", + "esprima": "1.0.x", + "fileset": "0.1.x", + "handlebars": "1.0.x", + "mkdirp": "0.3.x", + "nopt": "2.1.x", + "resolve": "0.5.x", + "which": "1.0.x", + "wordwrap": "0.0.x" + }, + "bin": { + "istanbul": "lib/cli.js" + } + }, + "node_modules/json3": { + "version": "3.3.2", + "resolved": "http://npm.tescloud.com/json3/-/json3-3.3.2.tgz", + "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=", + "dev": true + }, + "node_modules/kind-of": { + "version": "3.2.2", + "resolved": "http://npm.tescloud.com/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "dependencies": { + "is-buffer": "^1.1.5" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lazy-cache": { + "version": "1.0.4", + "resolved": "http://npm.tescloud.com/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lodash._baseassign": { + "version": "3.2.0", + "resolved": "http://npm.tescloud.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz", + "integrity": "sha1-jDigmVAPIVrQnlnxci/QxSv+Ck4=", + "dev": true, + "dependencies": { + "lodash._basecopy": "^3.0.0", + "lodash.keys": "^3.0.0" + } + }, + "node_modules/lodash._basecopy": { + "version": "3.0.1", + "resolved": "http://npm.tescloud.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", + "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", + "dev": true + }, + "node_modules/lodash._basecreate": { + "version": "3.0.3", + "resolved": "http://npm.tescloud.com/lodash._basecreate/-/lodash._basecreate-3.0.3.tgz", + "integrity": "sha1-G8ZhYU2qf8MRt9A78WgGoCE8+CE=", + "dev": true + }, + "node_modules/lodash._getnative": { + "version": "3.9.1", + "resolved": "http://npm.tescloud.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz", + "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", + "dev": true + }, + "node_modules/lodash._isiterateecall": { + "version": "3.0.9", + "resolved": "http://npm.tescloud.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", + "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", + "dev": true + }, + "node_modules/lodash.create": { + "version": "3.1.1", + "resolved": "http://npm.tescloud.com/lodash.create/-/lodash.create-3.1.1.tgz", + "integrity": "sha1-1/KEnw29p+BGgruM1yqwIkYd6+c=", + "dev": true, + "dependencies": { + "lodash._baseassign": "^3.0.0", + "lodash._basecreate": "^3.0.0", + "lodash._isiterateecall": "^3.0.0" + } + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "http://npm.tescloud.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", + "dev": true + }, + "node_modules/lodash.isarray": { + "version": "3.0.4", + "resolved": "http://npm.tescloud.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz", + "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", + "dev": true + }, + "node_modules/lodash.keys": { + "version": "3.1.2", + "resolved": "http://npm.tescloud.com/lodash.keys/-/lodash.keys-3.1.2.tgz", + "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", + "dev": true, + "dependencies": { + "lodash._getnative": "^3.0.0", + "lodash.isarguments": "^3.0.0", + "lodash.isarray": "^3.0.0" + } + }, + "node_modules/longest": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/longest/-/longest-1.0.1.tgz", + "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/lru-cache": { + "version": "2.7.3", + "resolved": "http://npm.tescloud.com/lru-cache/-/lru-cache-2.7.3.tgz", + "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", + "dev": true + }, + "node_modules/minimatch": { + "version": "0.4.0", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-0.4.0.tgz", + "integrity": "sha1-vSx9Bg0sjI/Xzefx8u0tWycP2xs=", + "dev": true, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "0.0.8", + "resolved": "http://npm.tescloud.com/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "node_modules/mkdirp": { + "version": "0.3.5", + "resolved": "http://npm.tescloud.com/mkdirp/-/mkdirp-0.3.5.tgz", + "integrity": "sha1-3j5fiWHIjHh+4TaN+EmsRBPsqNc=", + "dev": true + }, + "node_modules/mocha": { + "version": "3.5.3", + "resolved": "http://npm.tescloud.com/mocha/-/mocha-3.5.3.tgz", + "integrity": "sha512-/6na001MJWEtYxHOV1WLfsmR4YIynkUEhBwzsb+fk2qmQ3iqsi258l/Q2MWHJMImAcNpZ8DEdYAK72NHoIQ9Eg==", + "dev": true, + "dependencies": { + "browser-stdout": "1.3.0", + "commander": "2.9.0", + "debug": "2.6.8", + "diff": "3.2.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.1", + "growl": "1.9.2", + "he": "1.1.1", + "json3": "3.3.2", + "lodash.create": "3.1.1", + "mkdirp": "0.5.1", + "supports-color": "3.1.2" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha" + }, + "engines": { + "node": ">= 0.10.x", + "npm": ">= 1.4.x" + } + }, + "node_modules/mocha/node_modules/glob": { + "version": "7.1.1", + "resolved": "http://npm.tescloud.com/glob/-/glob-7.1.1.tgz", + "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.2", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "3.0.4", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/mkdirp": { + "version": "0.5.1", + "resolved": "http://npm.tescloud.com/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "dependencies": { + "minimist": "0.0.8" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "http://npm.tescloud.com/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "node_modules/nopt": { + "version": "2.1.2", + "resolved": "http://npm.tescloud.com/nopt/-/nopt-2.1.2.tgz", + "integrity": "sha1-bMzZd7gBMqB3MdbozljCyDA8+a8=", + "dev": true, + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "http://npm.tescloud.com/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/optimist": { + "version": "0.3.7", + "resolved": "http://npm.tescloud.com/optimist/-/optimist-0.3.7.tgz", + "integrity": "sha1-yQlBrVnkJzMokjB00s8ufLxuwNk=", + "dev": true, + "dependencies": { + "wordwrap": "~0.0.2" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/prelude-ls": { + "version": "0.6.0", + "resolved": "http://npm.tescloud.com/prelude-ls/-/prelude-ls-0.6.0.tgz", + "integrity": "sha1-z4JLS0fMc8vZb56YhQc7Q6rqqzs=", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==" + }, + "node_modules/readable-stream": { + "version": "1.1.14", + "resolved": "http://npm.tescloud.com/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "http://npm.tescloud.com/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, + "node_modules/resolve": { + "version": "0.5.1", + "resolved": "http://npm.tescloud.com/resolve/-/resolve-0.5.1.tgz", + "integrity": "sha1-FeSiIsQja81M+FRUQSwtD7ZSRXY=", + "dev": true + }, + "node_modules/right-align": { + "version": "0.1.3", + "resolved": "http://npm.tescloud.com/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", + "dev": true, + "dependencies": { + "align-text": "^0.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/sigmund": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/sigmund/-/sigmund-1.0.1.tgz", + "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", + "dev": true + }, + "node_modules/source-map": { + "version": "0.7.3", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "optional": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/string_decoder": { + "version": "0.10.31", + "resolved": "http://npm.tescloud.com/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + }, + "node_modules/supports-color": { + "version": "3.1.2", + "resolved": "http://npm.tescloud.com/supports-color/-/supports-color-3.1.2.tgz", + "integrity": "sha1-cqJiiU2dQIuVbKBf83su2KbiotU=", + "dev": true, + "dependencies": { + "has-flag": "^1.0.0" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/uglify-js": { + "version": "2.8.29", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", + "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", + "dev": true, + "dependencies": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + }, + "optionalDependencies": { + "uglify-to-browserify": "~1.0.0" + } + }, + "node_modules/uglify-js/node_modules/source-map": { + "version": "0.5.7", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/uglify-to-browserify": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", + "dev": true, + "optional": true + }, + "node_modules/url-parse": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.1.tgz", + "integrity": "sha512-HOfCOUJt7iSYzEx/UqgtwKRMC6EU91NFhsCHMv9oM03VJcVo2Qrp8T8kI9D7amFf1cu+/3CEhgb3rF9zL7k85Q==", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/which": { + "version": "1.0.9", + "resolved": "http://npm.tescloud.com/which/-/which-1.0.9.tgz", + "integrity": "sha1-RgwdoPgQED0DIam2M6+eV15kSG8=", + "dev": true, + "bin": { + "which": "bin/which" + } + }, + "node_modules/window-size": { + "version": "0.1.0", + "resolved": "http://npm.tescloud.com/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/wordwrap": { + "version": "0.0.3", + "resolved": "http://npm.tescloud.com/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "node_modules/yargs": { + "version": "3.10.0", + "resolved": "http://npm.tescloud.com/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "dev": true, + "dependencies": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + }, + "dependencies": { + "abbrev": { + "version": "1.0.9", + "resolved": "http://npm.tescloud.com/abbrev/-/abbrev-1.0.9.tgz", + "integrity": "sha1-kbR5JYinc4wl813W9jdSovh3YTU=", + "dev": true + }, + "align-text": { + "version": "0.1.4", + "resolved": "http://npm.tescloud.com/align-text/-/align-text-0.1.4.tgz", + "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", + "dev": true, + "requires": { + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" + } + }, + "amdefine": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/amdefine/-/amdefine-1.0.1.tgz", + "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", + "dev": true + }, + "async": { + "version": "0.2.10", + "resolved": "http://npm.tescloud.com/async/-/async-0.2.10.tgz", + "integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E=", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bitsyntax": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.1.0.tgz", + "integrity": "sha512-ikAdCnrloKmFOugAfxWws89/fPc+nw0OOG1IzIE72uSOg/A3cYptKCjSUhDTuj7fhsJtzkzlv7l3b8PzRHLN0Q==", + "requires": { + "buffer-more-ints": "~1.0.0", + "debug": "~2.6.9", + "safe-buffer": "~5.1.2" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "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==" + } + } + }, + "bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + }, + "boo": { + "version": "1.2.4", + "resolved": "http://npm.tescloud.com/boo/-/boo-1.2.4.tgz", + "integrity": "sha1-szMxw2xK552C9P0ORJBgTLfFE7U=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "http://npm.tescloud.com/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.0", + "resolved": "http://npm.tescloud.com/browser-stdout/-/browser-stdout-1.3.0.tgz", + "integrity": "sha1-81HTKWnTL6XXpVZxVCY9korjvR8=", + "dev": true + }, + "buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==" + }, + "camelcase": { + "version": "1.2.1", + "resolved": "http://npm.tescloud.com/camelcase/-/camelcase-1.2.1.tgz", + "integrity": "sha1-m7UwTS4LVmmLLHWLCKPqqdqlijk=", + "dev": true + }, + "center-align": { + "version": "0.1.3", + "resolved": "http://npm.tescloud.com/center-align/-/center-align-0.1.3.tgz", + "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", + "dev": true, + "requires": { + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" + } + }, + "claire": { + "version": "0.4.1", + "resolved": "http://npm.tescloud.com/claire/-/claire-0.4.1.tgz", + "integrity": "sha1-ynDcEmHd2PJaGvq604BcOfziY7w=", + "dev": true, + "requires": { + "boo": "~1.2.4", + "flaw": "~0.1.0", + "prelude-ls": "~0.6.0" + } + }, + "cliui": { + "version": "2.1.0", + "resolved": "http://npm.tescloud.com/cliui/-/cliui-2.1.0.tgz", + "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", + "dev": true, + "requires": { + "center-align": "^0.1.1", + "right-align": "^0.1.1", + "wordwrap": "0.0.2" + }, + "dependencies": { + "wordwrap": { + "version": "0.0.2", + "resolved": "http://npm.tescloud.com/wordwrap/-/wordwrap-0.0.2.tgz", + "integrity": "sha1-t5Zpu0LstAn4PVg8rVLKF+qhZD8=", + "dev": true + } + } + }, + "commander": { + "version": "2.9.0", + "resolved": "http://npm.tescloud.com/commander/-/commander-2.9.0.tgz", + "integrity": "sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q=", + "dev": true, + "requires": { + "graceful-readlink": ">= 1.0.0" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "http://npm.tescloud.com/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "debug": { + "version": "2.6.8", + "resolved": "http://npm.tescloud.com/debug/-/debug-2.6.8.tgz", + "integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw=", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "http://npm.tescloud.com/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "diff": { + "version": "3.2.0", + "resolved": "http://npm.tescloud.com/diff/-/diff-3.2.0.tgz", + "integrity": "sha1-yc45Okt8vQsFinJck98pkCeGj/k=", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "http://npm.tescloud.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "0.0.23", + "resolved": "http://npm.tescloud.com/escodegen/-/escodegen-0.0.23.tgz", + "integrity": "sha1-ms+XgWQ2jkInZXHxiDnII7OoRN8=", + "dev": true, + "requires": { + "esprima": "~1.0.2", + "estraverse": "~0.0.4", + "source-map": ">= 0.1.2" + } + }, + "esprima": { + "version": "1.0.4", + "resolved": "http://npm.tescloud.com/esprima/-/esprima-1.0.4.tgz", + "integrity": "sha1-n1V+CPw7TSbs6d00+Pv0drYlha0=", + "dev": true + }, + "estraverse": { + "version": "0.0.4", + "resolved": "http://npm.tescloud.com/estraverse/-/estraverse-0.0.4.tgz", + "integrity": "sha1-AaCTLf7ldGhKWYr1pnw7+bZCjbI=", + "dev": true + }, + "fileset": { + "version": "0.1.8", + "resolved": "http://npm.tescloud.com/fileset/-/fileset-0.1.8.tgz", + "integrity": "sha1-UGuRqTluqn4y+0KoQHfHoMc2t0E=", + "dev": true, + "requires": { + "glob": "3.x", + "minimatch": "0.x" + } + }, + "flaw": { + "version": "0.1.0", + "resolved": "http://npm.tescloud.com/flaw/-/flaw-0.1.0.tgz", + "integrity": "sha1-wMPo+BYWdTh+2tofbOhNZ5sCUn8=", + "dev": true + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "glob": { + "version": "3.2.11", + "resolved": "http://npm.tescloud.com/glob/-/glob-3.2.11.tgz", + "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", + "dev": true, + "requires": { + "inherits": "2", + "minimatch": "0.3" + }, + "dependencies": { + "minimatch": { + "version": "0.3.0", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-0.3.0.tgz", + "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", + "dev": true, + "requires": { + "lru-cache": "2", + "sigmund": "~1.0.0" + } + } + } + }, + "graceful-readlink": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz", + "integrity": "sha1-TK+tdrxi8C+gObL5Tpo906ORpyU=", + "dev": true + }, + "growl": { + "version": "1.9.2", + "resolved": "http://npm.tescloud.com/growl/-/growl-1.9.2.tgz", + "integrity": "sha1-Dqd0NxXbjY3ixe3hd14bRayFwC8=", + "dev": true + }, + "handlebars": { + "version": "1.0.12", + "resolved": "http://npm.tescloud.com/handlebars/-/handlebars-1.0.12.tgz", + "integrity": "sha1-GMbTRAw16RsZs/9YK5FRq0mF1Pw=", + "dev": true, + "requires": { + "optimist": "~0.3", + "uglify-js": "~2.3" + }, + "dependencies": { + "source-map": { + "version": "0.1.43", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.1.43.tgz", + "integrity": "sha1-wkvBRspRfBRx9drL4lcbK3+eM0Y=", + "dev": true, + "requires": { + "amdefine": ">=0.0.4" + } + }, + "uglify-js": { + "version": "2.3.6", + "resolved": "http://npm.tescloud.com/uglify-js/-/uglify-js-2.3.6.tgz", + "integrity": "sha1-+gmEdwtCi3qbKoBY9GNV0U/vIRo=", + "dev": true, + "requires": { + "async": "~0.2.6", + "optimist": "~0.3.5", + "source-map": "~0.1.7" + } + } + } + }, + "has-flag": { + "version": "1.0.0", + "resolved": "http://npm.tescloud.com/has-flag/-/has-flag-1.0.0.tgz", + "integrity": "sha1-nZ55MWXOAXoA8AQYxD+UKnsdEfo=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "http://npm.tescloud.com/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "http://npm.tescloud.com/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "http://npm.tescloud.com/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "http://npm.tescloud.com/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "isarray": { + "version": "0.0.1", + "resolved": "http://npm.tescloud.com/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "istanbul": { + "version": "0.1.46", + "resolved": "http://npm.tescloud.com/istanbul/-/istanbul-0.1.46.tgz", + "integrity": "sha1-zv6xx4fRJabbI70PY7Drk5CwtA0=", + "dev": true, + "requires": { + "abbrev": "1.0.x", + "async": "0.2.x", + "escodegen": "0.0.23", + "esprima": "1.0.x", + "fileset": "0.1.x", + "handlebars": "1.0.x", + "mkdirp": "0.3.x", + "nopt": "2.1.x", + "resolve": "0.5.x", + "which": "1.0.x", + "wordwrap": "0.0.x" + } + }, + "json3": { + "version": "3.3.2", + "resolved": "http://npm.tescloud.com/json3/-/json3-3.3.2.tgz", + "integrity": "sha1-PAQ0dD35Pi9cQq7nsZvLSDV19OE=", + "dev": true + }, + "kind-of": { + "version": "3.2.2", + "resolved": "http://npm.tescloud.com/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + }, + "lazy-cache": { + "version": "1.0.4", + "resolved": "http://npm.tescloud.com/lazy-cache/-/lazy-cache-1.0.4.tgz", + "integrity": "sha1-odePw6UEdMuAhF07O24dpJpEbo4=", + "dev": true + }, + "lodash._baseassign": { + "version": "3.2.0", + "resolved": "http://npm.tescloud.com/lodash._baseassign/-/lodash._baseassign-3.2.0.tgz", + "integrity": "sha1-jDigmVAPIVrQnlnxci/QxSv+Ck4=", + "dev": true, + "requires": { + "lodash._basecopy": "^3.0.0", + "lodash.keys": "^3.0.0" + } + }, + "lodash._basecopy": { + "version": "3.0.1", + "resolved": "http://npm.tescloud.com/lodash._basecopy/-/lodash._basecopy-3.0.1.tgz", + "integrity": "sha1-jaDmqHbPNEwK2KVIghEd08XHyjY=", + "dev": true + }, + "lodash._basecreate": { + "version": "3.0.3", + "resolved": "http://npm.tescloud.com/lodash._basecreate/-/lodash._basecreate-3.0.3.tgz", + "integrity": "sha1-G8ZhYU2qf8MRt9A78WgGoCE8+CE=", + "dev": true + }, + "lodash._getnative": { + "version": "3.9.1", + "resolved": "http://npm.tescloud.com/lodash._getnative/-/lodash._getnative-3.9.1.tgz", + "integrity": "sha1-VwvH3t5G1hzc3mh9ZdPuy6o6r/U=", + "dev": true + }, + "lodash._isiterateecall": { + "version": "3.0.9", + "resolved": "http://npm.tescloud.com/lodash._isiterateecall/-/lodash._isiterateecall-3.0.9.tgz", + "integrity": "sha1-UgOte6Ql+uhCRg5pbbnPPmqsBXw=", + "dev": true + }, + "lodash.create": { + "version": "3.1.1", + "resolved": "http://npm.tescloud.com/lodash.create/-/lodash.create-3.1.1.tgz", + "integrity": "sha1-1/KEnw29p+BGgruM1yqwIkYd6+c=", + "dev": true, + "requires": { + "lodash._baseassign": "^3.0.0", + "lodash._basecreate": "^3.0.0", + "lodash._isiterateecall": "^3.0.0" + } + }, + "lodash.isarguments": { + "version": "3.1.0", + "resolved": "http://npm.tescloud.com/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha1-L1c9hcaiQon/AGY7SRwdM4/zRYo=", + "dev": true + }, + "lodash.isarray": { + "version": "3.0.4", + "resolved": "http://npm.tescloud.com/lodash.isarray/-/lodash.isarray-3.0.4.tgz", + "integrity": "sha1-eeTriMNqgSKvhvhEqpvNhRtfu1U=", + "dev": true + }, + "lodash.keys": { + "version": "3.1.2", + "resolved": "http://npm.tescloud.com/lodash.keys/-/lodash.keys-3.1.2.tgz", + "integrity": "sha1-TbwEcrFWvlCgsoaFXRvQsMZWCYo=", + "dev": true, + "requires": { + "lodash._getnative": "^3.0.0", + "lodash.isarguments": "^3.0.0", + "lodash.isarray": "^3.0.0" + } + }, + "longest": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/longest/-/longest-1.0.1.tgz", + "integrity": "sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=", + "dev": true + }, + "lru-cache": { + "version": "2.7.3", + "resolved": "http://npm.tescloud.com/lru-cache/-/lru-cache-2.7.3.tgz", + "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", + "dev": true + }, + "minimatch": { + "version": "0.4.0", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-0.4.0.tgz", + "integrity": "sha1-vSx9Bg0sjI/Xzefx8u0tWycP2xs=", + "dev": true, + "requires": { + "lru-cache": "2", + "sigmund": "~1.0.0" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "http://npm.tescloud.com/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.3.5", + "resolved": "http://npm.tescloud.com/mkdirp/-/mkdirp-0.3.5.tgz", + "integrity": "sha1-3j5fiWHIjHh+4TaN+EmsRBPsqNc=", + "dev": true + }, + "mocha": { + "version": "3.5.3", + "resolved": "http://npm.tescloud.com/mocha/-/mocha-3.5.3.tgz", + "integrity": "sha512-/6na001MJWEtYxHOV1WLfsmR4YIynkUEhBwzsb+fk2qmQ3iqsi258l/Q2MWHJMImAcNpZ8DEdYAK72NHoIQ9Eg==", + "dev": true, + "requires": { + "browser-stdout": "1.3.0", + "commander": "2.9.0", + "debug": "2.6.8", + "diff": "3.2.0", + "escape-string-regexp": "1.0.5", + "glob": "7.1.1", + "growl": "1.9.2", + "he": "1.1.1", + "json3": "3.3.2", + "lodash.create": "3.1.1", + "mkdirp": "0.5.1", + "supports-color": "3.1.2" + }, + "dependencies": { + "glob": { + "version": "7.1.1", + "resolved": "http://npm.tescloud.com/glob/-/glob-7.1.1.tgz", + "integrity": "sha1-gFIR3wT6rxxjo2ADBs31reULLsg=", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.2", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "http://npm.tescloud.com/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://npm.tescloud.com/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + } + } + }, + "ms": { + "version": "2.0.0", + "resolved": "http://npm.tescloud.com/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "nopt": { + "version": "2.1.2", + "resolved": "http://npm.tescloud.com/nopt/-/nopt-2.1.2.tgz", + "integrity": "sha1-bMzZd7gBMqB3MdbozljCyDA8+a8=", + "dev": true, + "requires": { + "abbrev": "1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "http://npm.tescloud.com/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "optimist": { + "version": "0.3.7", + "resolved": "http://npm.tescloud.com/optimist/-/optimist-0.3.7.tgz", + "integrity": "sha1-yQlBrVnkJzMokjB00s8ufLxuwNk=", + "dev": true, + "requires": { + "wordwrap": "~0.0.2" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "prelude-ls": { + "version": "0.6.0", + "resolved": "http://npm.tescloud.com/prelude-ls/-/prelude-ls-0.6.0.tgz", + "integrity": "sha1-z4JLS0fMc8vZb56YhQc7Q6rqqzs=", + "dev": true + }, + "querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==" + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "http://npm.tescloud.com/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "http://npm.tescloud.com/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, + "resolve": { + "version": "0.5.1", + "resolved": "http://npm.tescloud.com/resolve/-/resolve-0.5.1.tgz", + "integrity": "sha1-FeSiIsQja81M+FRUQSwtD7ZSRXY=", + "dev": true + }, + "right-align": { + "version": "0.1.3", + "resolved": "http://npm.tescloud.com/right-align/-/right-align-0.1.3.tgz", + "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", + "dev": true, + "requires": { + "align-text": "^0.1.1" + } + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "sigmund": { + "version": "1.0.1", + "resolved": "http://npm.tescloud.com/sigmund/-/sigmund-1.0.1.tgz", + "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", + "dev": true + }, + "source-map": { + "version": "0.7.3", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "optional": true + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "http://npm.tescloud.com/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + }, + "supports-color": { + "version": "3.1.2", + "resolved": "http://npm.tescloud.com/supports-color/-/supports-color-3.1.2.tgz", + "integrity": "sha1-cqJiiU2dQIuVbKBf83su2KbiotU=", + "dev": true, + "requires": { + "has-flag": "^1.0.0" + } + }, + "uglify-js": { + "version": "2.8.29", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", + "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", + "dev": true, + "requires": { + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" + }, + "dependencies": { + "source-map": { + "version": "0.5.7", + "resolved": "http://npm.tescloud.com/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + } + } + }, + "uglify-to-browserify": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/uglify-to-browserify/-/uglify-to-browserify-1.0.2.tgz", + "integrity": "sha1-bgkk1r2mta/jSeOabWMoUKD4grc=", + "dev": true, + "optional": true + }, + "url-parse": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.1.tgz", + "integrity": "sha512-HOfCOUJt7iSYzEx/UqgtwKRMC6EU91NFhsCHMv9oM03VJcVo2Qrp8T8kI9D7amFf1cu+/3CEhgb3rF9zL7k85Q==", + "requires": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "which": { + "version": "1.0.9", + "resolved": "http://npm.tescloud.com/which/-/which-1.0.9.tgz", + "integrity": "sha1-RgwdoPgQED0DIam2M6+eV15kSG8=", + "dev": true + }, + "window-size": { + "version": "0.1.0", + "resolved": "http://npm.tescloud.com/window-size/-/window-size-0.1.0.tgz", + "integrity": "sha1-VDjNLqk7IC76Ohn+iIeu58lPnJ0=", + "dev": true + }, + "wordwrap": { + "version": "0.0.3", + "resolved": "http://npm.tescloud.com/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true + }, + "wrappy": { + "version": "1.0.2", + "resolved": "http://npm.tescloud.com/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "yargs": { + "version": "3.10.0", + "resolved": "http://npm.tescloud.com/yargs/-/yargs-3.10.0.tgz", + "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", + "dev": true, + "requires": { + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", + "window-size": "0.1.0" + } + } + } +} diff --git a/node_modules/amqplib/package.json b/node_modules/amqplib/package.json new file mode 100644 index 0000000..3474a5c --- /dev/null +++ b/node_modules/amqplib/package.json @@ -0,0 +1,71 @@ +{ + "_from": "amqplib", + "_id": "amqplib@0.8.0", + "_inBundle": false, + "_integrity": "sha512-icU+a4kkq4Y1PS4NNi+YPDMwdlbFcZ1EZTQT2nigW3fvOb6AOgUQ9+Mk4ue0Zu5cBg/XpDzB40oH10ysrk2dmA==", + "_location": "/amqplib", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "amqplib", + "name": "amqplib", + "escapedName": "amqplib", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.8.0.tgz", + "_shasum": "088d10bc61cc5ac5a49ac72033c7ac66c23aeb61", + "_spec": "amqplib", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq", + "author": { + "name": "Michael Bridgen", + "email": "mikeb@squaremobius.net" + }, + "bugs": { + "url": "https://github.com/squaremo/amqp.node/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bitsyntax": "~0.1.0", + "bluebird": "^3.7.2", + "buffer-more-ints": "~1.0.0", + "readable-stream": "1.x >=1.1.9", + "safe-buffer": "~5.2.1", + "url-parse": "~1.5.1" + }, + "deprecated": false, + "description": "An AMQP 0-9-1 (e.g., RabbitMQ) library and client.", + "devDependencies": { + "claire": "0.4.1", + "istanbul": "0.1.x", + "mocha": "^3.5.3", + "uglify-js": "2.8.x" + }, + "engines": { + "node": ">=10" + }, + "homepage": "http://squaremo.github.io/amqp.node/", + "keywords": [ + "AMQP", + "AMQP 0-9-1", + "RabbitMQ" + ], + "license": "MIT", + "main": "./channel_api.js", + "name": "amqplib", + "repository": { + "type": "git", + "url": "git+https://github.com/squaremo/amqp.node.git" + }, + "scripts": { + "prepare": "make", + "test": "make test" + }, + "version": "0.8.0" +} diff --git a/node_modules/amqplib/test/bitset.js b/node_modules/amqplib/test/bitset.js new file mode 100644 index 0000000..35e7656 --- /dev/null +++ b/node_modules/amqplib/test/bitset.js @@ -0,0 +1,68 @@ +'use strict'; + +var claire = require('claire'); + +var forAll = claire.forAll, + arb = claire.data, + label = claire.label, + choice = claire.choice, + transform = claire.transform; + +var BitSet = require('../lib/bitset').BitSet; +var PosInt = transform(Math.floor, arb.Positive); + +var EmptyBitSet = label('bitset', transform( + function(size) { + return new BitSet(size); + }, + choice(arb.Nothing, PosInt))); + +suite('BitSet', function() { + +test('get bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.get(bit); + }).asTest()); + +test('clear bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + b.clear(bit); + return !b.get(bit); + }).asTest()); + +test('next set of empty', forAll(EmptyBitSet) + .satisfy(function(b) { + return b.nextSetBit(0) === -1; + }).asTest()); + +test('next set of one bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(0) === bit; + }).asTest()); + +test('next set same bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(bit) === bit; + }).asTest()); + +test('next set following bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(bit+1) === -1; + }).asTest()); + +test('next clear of empty', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { return b.nextClearBit(bit) === bit; }) + .asTest()); + +test('next clear of one set', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextClearBit(bit) === bit + 1; + }).asTest()); + +}); diff --git a/node_modules/amqplib/test/callback_api.js b/node_modules/amqplib/test/callback_api.js new file mode 100644 index 0000000..5aea0bf --- /dev/null +++ b/node_modules/amqplib/test/callback_api.js @@ -0,0 +1,313 @@ +'use strict'; + +var assert = require('assert'); +var crypto = require('crypto'); +var api = require('../callback_api'); +var util = require('./util'); +var schedule = util.schedule; +var randomString = util.randomString; +var kCallback = util.kCallback; +var domain = require('domain'); +var Buffer = require('safe-buffer').Buffer; + +var URL = process.env.URL || 'amqp://localhost'; + +function connect(cb) { + api.connect(URL, {}, cb); +} + +// Construct a node-style callback from a `done` function +function doneCallback(done) { + return function(err, _) { + if (err == null) done(); + else done(err); + }; +} + +function ignore() {} + +function twice(done) { + var first = function(err) { + if (err == undefined) second = done; + else second = ignore, done(err); + }; + var second = function(err) { + if (err == undefined) first = done; + else first = ignore, done(err); + }; + return {first: function(err) { first(err); }, + second: function(err) { second(err); }}; +} + +// Adapt 'done' to a callback that's expected to fail +function failCallback(done) { + return function(err, _) { + if (err == null) done(new Error('Expected failure, got ' + val)); + else done(); + }; +} + +function waitForMessages(ch, q, k) { + ch.checkQueue(q, function(e, ok) { + if (e != null) return k(e); + else if (ok.messageCount > 0) return k(null, ok); + else schedule(waitForMessages.bind(null, ch, q, k)); + }); +} + + +suite('connect', function() { + +test('at all', function(done) { + connect(doneCallback(done)); +}); + +}); + +function channel_test_fn(method) { + return function(name, chfun) { + test(name, function(done) { + connect(kCallback(function(c) { + c[method](kCallback(function(ch) { + chfun(ch, done); + }, done)); + }, done)); + }); + }; +} +var channel_test = channel_test_fn('createChannel'); +var confirm_channel_test = channel_test_fn('createConfirmChannel'); + +suite('channel open', function() { + +channel_test('at all', function(ch, done) { + done(); +}); + +channel_test('open and close', function(ch, done) { + ch.close(doneCallback(done)); +}); + +}); + +suite('assert, check, delete', function() { + +channel_test('assert, check, delete queue', function(ch, done) { + ch.assertQueue('test.cb.queue', {}, kCallback(function(q) { + ch.checkQueue('test.cb.queue', kCallback(function(ok) { + ch.deleteQueue('test.cb.queue', {}, doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('assert, check, delete exchange', function(ch, done) { + ch.assertExchange( + 'test.cb.exchange', 'topic', {}, kCallback(function(ex) { + ch.checkExchange('test.cb.exchange', kCallback(function(ok) { + ch.deleteExchange('test.cb.exchange', {}, doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('fail on check non-queue', function(ch, done) { + var both = twice(done); + ch.on('error', failCallback(both.first)); + ch.checkQueue('test.cb.nothere', failCallback(both.second)); +}); + +channel_test('fail on check non-exchange', function(ch, done) { + var both = twice(done); + ch.on('error', failCallback(both.first)); + ch.checkExchange('test.cb.nothere', failCallback(both.second)); +}); + +}); + +suite('bindings', function() { + +channel_test('bind queue', function(ch, done) { + ch.assertQueue('test.cb.bindq', {}, kCallback(function(q) { + ch.assertExchange( + 'test.cb.bindex', 'fanout', {}, kCallback(function(ex) { + ch.bindQueue(q.queue, ex.exchange, '', {}, + doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('bind exchange', function(ch, done) { + ch.assertExchange( + 'test.cb.bindex1', 'fanout', {}, kCallback(function(ex1) { + ch.assertExchange( + 'test.cb.bindex2', 'fanout', {}, kCallback(function(ex2) { + ch.bindExchange(ex1.exchange, + ex2.exchange, '', {}, + doneCallback(done)); + }, done)); + }, done)); +}); + +}); + +suite('sending messages', function() { + +channel_test('send to queue and consume noAck', function(ch, done) { + var msg = randomString(); + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e !== null) return done(e); + ch.consume(q.queue, function(m) { + if (m.content.toString() == msg) done(); + else done(new Error("message content doesn't match:" + + msg + " =/= " + m.content.toString())); + }, {noAck: true, exclusive: true}); + ch.sendToQueue(q.queue, Buffer.from(msg)); + }); +}); + +channel_test('send to queue and consume ack', function(ch, done) { + var msg = randomString(); + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e !== null) return done(e); + ch.consume(q.queue, function(m) { + if (m.content.toString() == msg) { + ch.ack(m); + done(); + } + else done(new Error("message content doesn't match:" + + msg + " =/= " + m.content.toString())); + }, {noAck: false, exclusive: true}); + ch.sendToQueue(q.queue, Buffer.from(msg)); + }); +}); + +channel_test('send to and get from queue', function(ch, done) { + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e != null) return done(e); + var msg = randomString(); + ch.sendToQueue(q.queue, Buffer.from(msg)); + waitForMessages(ch, q.queue, function(e, _) { + if (e != null) return done(e); + ch.get(q.queue, {noAck: true}, function(e, m) { + if (e != null) + return done(e); + else if (!m) + return done(new Error('Empty (false) not expected')); + else if (m.content.toString() == msg) + return done(); + else + return done( + new Error('Messages do not match: ' + + msg + ' =/= ' + m.content.toString())); + }); + }); + }); +}); + +}); + +suite('ConfirmChannel', function() { + +confirm_channel_test('Receive confirmation', function(ch, done) { + // An unroutable message, on the basis that you're not allowed a + // queue with an empty name, and you can't make bindings to the + // default exchange. Tricky eh? + ch.publish('', '', Buffer.from('foo'), {}, done); +}); + +confirm_channel_test('Wait for confirms', function(ch, done) { + for (var i=0; i < 1000; i++) { + ch.publish('', '', Buffer.from('foo'), {}); + } + ch.waitForConfirms(done); +}); + +}); + +suite("Error handling", function() { + +/* +I don't like having to do this, but there appears to be something +broken about domains in Node.JS v0.8 and mocha. Apparently it has to +do with how mocha and domains hook into error propogation: +https://github.com/visionmedia/mocha/issues/513 (summary: domains in +Node.JS v0.8 don't prevent uncaughtException from firing, and that's +what mocha uses to detect .. an uncaught exception). + +Using domains with amqplib *does* work in practice in Node.JS v0.8: +that is, it's possible to throw an exception in a callback and deal +with it in the active domain, and thereby avoid it crashing the +program. + */ +if (util.versionGreaterThan(process.versions.node, '0.8')) { + test('Throw error in connection open callback', function(done) { + var dom = domain.createDomain(); + dom.on('error', failCallback(done)); + connect(dom.bind(function(err, conn) { + throw new Error('Spurious connection open callback error'); + })); + }); +} + +// TODO: refactor {error_test, channel_test} +function error_test(name, fun) { + test(name, function(done) { + var dom = domain.createDomain(); + dom.run(function() { + connect(kCallback(function(c) { + // Seems like there were some unironed wrinkles in 0.8's + // implementation of domains; explicitly adding the connection + // to the domain makes sure any exception thrown in the course + // of processing frames is handled by the domain. For other + // versions of Node.JS, this ends up being belt-and-braces. + dom.add(c); + c.createChannel(kCallback(function(ch) { + fun(ch, done, dom); + }, done)); + }, done)); + }); + }); +} + +error_test('Channel open callback throws an error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + throw new Error('Error in open callback'); +}); + +error_test('RPC callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.prefetch(0, false, function(err, ok) { + throw new Error('Spurious callback error'); + }); +}); + +error_test('Get callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.assertQueue('test.cb.get-with-error', {}, function(err, ok) { + ch.get('test.cb.get-with-error', {noAck: true}, function() { + throw new Error('Spurious callback error'); + }); + }); +}); + +error_test('Consume callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.assertQueue('test.cb.consume-with-error', {}, function(err, ok) { + ch.consume('test.cb.consume-with-error', ignore, {noAck: true}, function() { + throw new Error('Spurious callback error'); + }); + }); +}); + +error_test('Get from non-queue invokes error k', function(ch, done, dom) { + var both = twice(failCallback(done)); + dom.on('error', both.first); + ch.get('', {}, both.second); +}); + +error_test('Consume from non-queue invokes error k', function(ch, done, dom) { + var both = twice(failCallback(done)); + dom.on('error', both.first); + ch.consume('', both.second); +}); + +}); diff --git a/node_modules/amqplib/test/channel.js b/node_modules/amqplib/test/channel.js new file mode 100644 index 0000000..072c335 --- /dev/null +++ b/node_modules/amqplib/test/channel.js @@ -0,0 +1,624 @@ +// Test the channel machinery + +'use strict'; + +var assert = require('assert'); +var Promise = require('bluebird'); +var Channel = require('../lib/channel').Channel; +var Connection = require('../lib/connection').Connection; +var util = require('./util'); +var succeed = util.succeed, fail = util.fail, latch = util.latch; +var completes = util.completes; +var defs = require('../lib/defs'); +var conn_handshake = require('./connection').connection_handshake; +var OPEN_OPTS = require('./connection').OPEN_OPTS; +var Buffer = require('safe-buffer').Buffer; + +var LOG_ERRORS = process.env.LOG_ERRORS; + +function baseChannelTest(client, server) { + return function(done) { + var bothDone = latch(2, done); + var pair = util.socketPair(); + var c = new Connection(pair.client); + + if (LOG_ERRORS) c.on('error', console.warn); + + c.open(OPEN_OPTS, function(err, ok) { + if (err === null) client(c, bothDone); + else fail(bothDone); + }); + + pair.server.read(8); // discard the protocol header + var s = util.runServer(pair.server, function(send, wait) { + conn_handshake(send, wait) + .then(function() { + server(send, wait, bothDone); + }, fail(bothDone)); + }); + }; +} + +function channelTest(client, server) { + return baseChannelTest( + function(conn, done) { + var ch = new Channel(conn); + if (LOG_ERRORS) ch.on('error', console.warn); + client(ch, done, conn); + }, + function(send, wait, done) { + channel_handshake(send, wait) + .then(function(ch) { + return server(send, wait, done, ch); + }).then(null, fail(done)); // so you can return a promise to let + // errors bubble out + } + ); +}; + +function channel_handshake(send, wait) { + return wait(defs.ChannelOpen)() + .then(function(open) { + assert.notEqual(0, open.channel); + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, open.channel); + return open.channel; + }); +} + +// fields for deliver and publish and get-ok +var DELIVER_FIELDS = { + consumerTag: 'fake', + deliveryTag: 1, + redelivered: false, + exchange: 'foo', + routingKey: 'bar', + replyCode: defs.constants.NO_ROUTE, + replyText: 'derp', +}; + +function open(ch) { + return Promise.try(function() { + ch.allocate(); + return Promise.fromCallback(function(cb) { + ch._rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk, cb); + }); + }); +} + +suite("channel open and close", function() { + +test("open", channelTest( + function(ch, done) { + open(ch).then(succeed(done), fail(done)); + }, + function(send, wait, done) { + done(); + })); + +test("bad server", baseChannelTest( + function(c, done) { + var ch = new Channel(c); + open(ch).then(fail(done), succeed(done)); + }, + function(send, wait, done) { + return wait(defs.ChannelOpen)() + .then(function(open) { + send(defs.ChannelCloseOk, {}, open.channel); + }).then(succeed(done), fail(done)); + })); + +test("open, close", channelTest( + function(ch, done) { + open(ch) + .then(function() { + return new Promise(function(resolve) { + ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS, resolve); + }); + }) + .then(succeed(done), fail(done)); + }, + function(send, wait, done, ch) { + return wait(defs.ChannelClose)() + .then(function(close) { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("server close", channelTest( + function(ch, done) { + ch.on('error', function(error) { + assert.strictEqual(504, error.code); + assert.strictEqual(0, error.classId); + assert.strictEqual(0, error.methodId); + succeed(done)(); + }); + open(ch); + }, + function(send, wait, done, ch) { + send(defs.ChannelClose, { + replyText: 'Forced close', + replyCode: defs.constants.CHANNEL_ERROR, + classId: 0, methodId: 0 + }, ch); + wait(defs.ChannelCloseOk)() + .then(succeed(done), fail(done)); + })); + +test("overlapping channel/server close", channelTest( + function(ch, done, conn) { + var both = latch(2, done); + conn.on('error', succeed(both)); + ch.on('close', succeed(both)); + open(ch).then(function() { + ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS); + }, fail(both)); + }, + function(send, wait, done, ch) { + wait(defs.ChannelClose)() + .then(function() { + send(defs.ConnectionClose, { + replyText: 'Got there first', + replyCode: defs.constants.INTERNAL_ERROR, + classId: 0, methodId: 0 + }, 0); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + +test("double close", channelTest( + function(ch, done) { + open(ch).then(function() { + ch.closeBecause("First close", defs.constants.REPLY_SUCCESS); + // NB no synchronisation, we do this straight away + assert.throws(function() { + ch.closeBecause("Second close", defs.constants.REPLY_SUCCESS); + }); + }).then(succeed(done), fail(done)); + }, + function(send, wait, done, ch) { + wait(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, { + }, ch); + }) + .then(succeed(done), fail(done)); + })); + +}); //suite + +suite("channel machinery", function() { + +test("RPC", channelTest( + function(ch, done) { + var rpcLatch = latch(3, done); + open(ch).then(function() { + + function wheeboom(err, f) { + if (err !== null) rpcLatch(err); + else rpcLatch(); + } + + var fields = { + prefetchCount: 10, + prefetchSize: 0, + global: false + }; + + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + }).then(null, fail(rpcLatch)); + }, + function(send, wait, done, ch) { + function sendOk(f) { + send(defs.BasicQosOk, {}, ch); + } + + return wait(defs.BasicQos)() + .then(sendOk) + .then(wait(defs.BasicQos)) + .then(sendOk) + .then(wait(defs.BasicQos)) + .then(sendOk) + .then(succeed(done), fail(done)); + })); + +test("Bad RPC", channelTest( + function(ch, done) { + // We want to see the RPC rejected and the channel closed (with an + // error) + var errLatch = latch(2, done); + ch.on('error', function(error) { + assert.strictEqual(505, error.code); + assert.strictEqual(60, error.classId); + assert.strictEqual(72, error.methodId); + succeed(errLatch)(); + }); + + open(ch) + .then(function() { + ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, + function(err) { + if (err !== null) errLatch(); + else errLatch(new Error('Expected RPC failure')); + }); + }, fail(errLatch)); + }, + function(send, wait, done, ch) { + return wait()() + .then(function() { + send(defs.BasicGetEmpty, {clusterId: ''}, ch); + }) // oh wait! that was wrong! expect a channel close + .then(wait(defs.ChannelClose)) + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("RPC on closed channel", channelTest( + function(ch, done) { + open(ch); + + var close = new Promise(function(resolve) { + ch.on('error', function(error) { + assert.strictEqual(504, error.code); + assert.strictEqual(0, error.classId); + assert.strictEqual(0, error.methodId); + resolve(); + }); + }); + + function failureCb(resolve, reject) { + return function(err) { + if (err !== null) resolve(); + else reject(); + } + } + + var fail1 = new Promise(function(resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, + failureCb(resolve, reject)); + }); + + var fail2 = new Promise(function(resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, + failureCb(resolve, reject)); + }); + + Promise.join(close, fail1, fail2) + .then(succeed(done)) + .catch(fail(done)); + }, + function(send, wait, done, ch) { + wait(defs.BasicRecover)() + .then(function() { + send(defs.ChannelClose, { + replyText: 'Nuh-uh!', + replyCode: defs.constants.CHANNEL_ERROR, + methodId: 0, classId: 0 + }, ch); + return wait(defs.ChannelCloseOk); + }) + .then(succeed(done)) + .catch(fail(done)); + })); + +test("publish all < single chunk threshold", channelTest( + function(ch, done) { + open(ch) + .then(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.from('foobar')); + }) + .then(succeed(done), fail(done)); + }, + function(send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function(f) { + assert.equal('foobar', f.content.toString()); + }).then(succeed(done), fail(done)); + })); + +test("publish content > single chunk threshold", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(3000)); + }, done); + }, + function(send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function(f) { + assert.equal(3000, f.content.length); + }).then(succeed(done), fail(done)); + })); + +test("publish method & headers > threshold", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, { + headers: {foo: Buffer.alloc(3000)} + }, Buffer.from('foobar')); + }, done); + }, + function(send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + .then(wait(undefined)) // content frame + .then(function(f) { + assert.equal('foobar', f.content.toString()); + }).then(succeed(done), fail(done)); + })); + +test("publish zero-length message", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(0)); + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(0)); + }, done); + }, + function(send, wait, done, ch) { + wait(defs.BasicPublish)() + .then(wait(defs.BasicProperties)) + // no content frame for a zero-length message + .then(wait(defs.BasicPublish)) + .then(succeed(done), fail(done)); + })); + +test("delivery", channelTest( + function(ch, done) { + open(ch); + ch.on('delivery', function(m) { + completes(function() { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + })); + +test("zero byte msg", channelTest( + function(ch, done) { + open(ch); + ch.on('delivery', function(m) { + completes(function() { + assert.deepEqual(Buffer.alloc(0), m.content); + }, done); + }); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('')); + }, done); + })); + +test("bad delivery", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('error', function(error) { + assert.strictEqual(505, error.code); + assert.strictEqual(60, error.classId); + assert.strictEqual(60, error.methodId); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function(send, wait, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + // now send another deliver without having sent the content + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + return wait(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("bad content send", channelTest( + function(ch, done) { + completes(function() { + open(ch); + assert.throws(function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {}, null); + }); + }, done); + }, + function(send, wait, done, ch) { + done(); + })); + +test("bad properties send", channelTest( + function(ch, done) { + completes(function() { + open(ch); + assert.throws(function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {contentEncoding: 7}, + Buffer.from('foobar')); + }); + }, done); + }, + function(send, wait, done, ch) { + done(); + })); + +test("bad consumer", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('delivery', function() { + throw new Error("I am a bad consumer"); + }); + ch.on('error', function(error) { + assert.strictEqual(541, error.code); + assert.strictEqual(undefined, error.classId); + assert.strictEqual(undefined, error.methodId); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function(send, wait, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + return wait(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("bad send in consumer", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('close', succeed(errorAndClose)); + ch.on('error', function(error) { + assert.strictEqual(541, error.code); + assert.strictEqual(undefined, error.classId); + assert.strictEqual(undefined, error.methodId); + succeed(errorAndClose)(); + }); + + ch.on('delivery', function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {}, null); // can't send null + }); + + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, + Buffer.from('barfoo')); + }, done); + return wait(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("return", channelTest( + function(ch, done) { + ch.on('return', function(m) { + completes(function() { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicReturn, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + })); + +test("cancel", channelTest( + function(ch, done) { + ch.on('cancel', function(f) { + completes(function() { + assert.equal('product of society', f.consumerTag); + }, done); + }); + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicCancel, { + consumerTag: 'product of society', + nowait: false + }, ch); + }, done); + })); + +function confirmTest(variety, Method) { + return test('confirm ' + variety, channelTest( + function(ch, done) { + ch.on(variety, function(f) { + completes(function() { + assert.equal(1, f.deliveryTag); + }, done); + }); + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(Method, { + deliveryTag: 1, + multiple: false + }, ch); + }, done); + })); +} + +confirmTest("ack", defs.BasicAck); +confirmTest("nack", defs.BasicNack); + +test("out-of-order acks", channelTest( + function(ch, done) { + var allConfirms = latch(3, function() { + completes(function() { + assert.equal(0, ch.unconfirmed.length); + assert.equal(4, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 3, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + })); + +test("not all out-of-order acks", channelTest( + function(ch, done) { + var allConfirms = latch(2, function() { + completes(function() { + assert.equal(1, ch.unconfirmed.length); + assert.equal(3, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); // tag = 1 + ch.pushConfirmCallback(allConfirms); // tag = 2 + ch.pushConfirmCallback(function() { + done(new Error('Confirm callback should not be called')); + }); + open(ch); + }, + function(send, wait, done, ch) { + completes(function() { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + })); + +}); diff --git a/node_modules/amqplib/test/channel_api.js b/node_modules/amqplib/test/channel_api.js new file mode 100644 index 0000000..bd5473f --- /dev/null +++ b/node_modules/amqplib/test/channel_api.js @@ -0,0 +1,597 @@ +'use strict'; + +var assert = require('assert'); +var api = require('../channel_api'); +var util = require('./util'); +var succeed = util.succeed, fail = util.fail; +var schedule = util.schedule; +var randomString = util.randomString; +var Promise = require('bluebird'); +var Buffer = require('safe-buffer').Buffer; + +var URL = process.env.URL || 'amqp://localhost'; + +function connect() { + return api.connect(URL); +} + +// Expect this promise to fail, and flip the results accordingly. +function expectFail(promise) { + return new Promise(function(resolve, reject) { + return promise.then(reject).catch(resolve); + }); +} + +// I'll rely on operations being rejected, rather than the channel +// close error, to detect failure. +function ignore () {} +function ignoreErrors(c) { + c.on('error', ignore); return c; +} +function logErrors(c) { + c.on('error', console.warn); return c; +} + +// Run a test with `name`, given a function that takes an open +// channel, and returns a promise that is resolved on test success or +// rejected on test failure. +function channel_test(chmethod, name, chfun) { + test(name, function(done) { + connect(URL).then(logErrors).then(function(c) { + c[chmethod]().then(ignoreErrors).then(chfun) + .then(succeed(done), fail(done)) + // close the connection regardless of what happens with the test + .finally(function() {c.close();}); + }); + }); +} + +var chtest = channel_test.bind(null, 'createChannel'); + +suite("connect", function() { + +test("at all", function(done) { + connect(URL).then(function(c) { + return c.close() + ;}).then(succeed(done), fail(done)); +}); + +chtest("create channel", ignore); // i.e., just don't bork + +}); + +var QUEUE_OPTS = {durable: false}; +var EX_OPTS = {durable: false}; + +suite("assert, check, delete", function() { + +chtest("assert and check queue", function(ch) { + return ch.assertQueue('test.check-queue', QUEUE_OPTS) + .then(function(qok) { + return ch.checkQueue('test.check-queue'); + }); +}); + +chtest("assert and check exchange", function(ch) { + return ch.assertExchange('test.check-exchange', 'direct', EX_OPTS) + .then(function(eok) { + assert.equal('test.check-exchange', eok.exchange); + return ch.checkExchange('test.check-exchange'); + }); +}); + +chtest("fail on reasserting queue with different options", + function(ch) { + var q = 'test.reassert-queue'; + return ch.assertQueue( + q, {durable: false, autoDelete: true}) + .then(function() { + return expectFail( + ch.assertQueue(q, {durable: false, + autoDelete: false})); + }); + }); + +chtest("fail on checking a queue that's not there", function(ch) { + return expectFail(ch.checkQueue('test.random-' + randomString())); +}); + +chtest("fail on checking an exchange that's not there", function(ch) { + return expectFail(ch.checkExchange('test.random-' + randomString())); +}); + +chtest("fail on reasserting exchange with different type", + function(ch) { + var ex = 'test.reassert-ex'; + return ch.assertExchange(ex, 'fanout', EX_OPTS) + .then(function() { + return expectFail( + ch.assertExchange(ex, 'direct', EX_OPTS)); + }); + }); + +chtest("channel break on publishing to non-exchange", function(ch) { + return new Promise(function(resolve) { + ch.on('error', resolve); + ch.publish(randomString(), '', Buffer.from('foobar')); + }); +}); + +chtest("delete queue", function(ch) { + var q = 'test.delete-queue'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.checkQueue(q)) + .then(function() { + return ch.deleteQueue(q);}) + .then(function() { + return expectFail(ch.checkQueue(q));}); +}); + +chtest("delete exchange", function(ch) { + var ex = 'test.delete-exchange'; + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.checkExchange(ex)) + .then(function() { + return ch.deleteExchange(ex);}) + .then(function() { + return expectFail(ch.checkExchange(ex));}); +}); + +}); + +// Wait for the queue to meet the condition; useful for waiting for +// messages to arrive, for example. +function waitForQueue(q, condition) { + return connect(URL).then(function(c) { + return c.createChannel() + .then(function(ch) { + return ch.checkQueue(q).then(function(qok) { + function check() { + return ch.checkQueue(q).then(function(qok) { + if (condition(qok)) { + c.close(); + return qok; + } + else schedule(check); + }); + } + return check(); + }); + }); + }); +} + +// Return a promise that resolves when the queue has at least `num` +// messages. If num is not supplied its assumed to be 1. +function waitForMessages(q, num) { + var min = (num === undefined) ? 1 : num; + return waitForQueue(q, function(qok) { + return qok.messageCount >= min; + }); +} + +suite("sendMessage", function() { + +// publish different size messages +chtest("send to queue and get from queue", function(ch) { + var q = 'test.send-to-q'; + var msg = randomString(); + return Promise.join(ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg)); + return waitForMessages(q); + }) + .then(function() { + return ch.get(q, {noAck: true}); + }) + .then(function(m) { + assert(m); + assert.equal(msg, m.content.toString()); + }); +}); + +chtest("send (and get) zero content to queue", function(ch) { + var q = 'test.send-to-q'; + var msg = Buffer.alloc(0); + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, msg); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(m); + assert.deepEqual(msg, m.content); + }); +}); + +}); + +suite("binding, consuming", function() { + +// bind, publish, get +chtest("route message", function(ch) { + var ex = 'test.route-message'; + var q = 'test.route-message-q'; + var msg = randomString(); + + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindQueue(q, ex, '', {})) + .then(function() { + ch.publish(ex, '', Buffer.from(msg)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(m); + assert.equal(msg, m.content.toString()); + }); +}); + +// send to queue, purge, get-empty +chtest("purge queue", function(ch) { + var q = 'test.purge-queue'; + return ch.assertQueue(q, {durable: false}) + .then(function() { + ch.sendToQueue(q, Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { + ch.purgeQueue(q); + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(!m); // get-empty + }); +}); + +// bind again, unbind, publish, get-empty +chtest("unbind queue", function(ch) { + var ex = 'test.unbind-queue-ex'; + var q = 'test.unbind-queue'; + var viabinding = randomString(); + var direct = randomString(); + + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindQueue(q, ex, '', {})) + .then(function() { + ch.publish(ex, '', Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { // message got through! + return ch.get(q, {noAck:true}) + .then(function(m) {assert(m);});}) + .then(function() { + return ch.unbindQueue(q, ex, '', {});}) + .then(function() { + // via the no-longer-existing binding + ch.publish(ex, '', Buffer.from(viabinding)); + // direct to the queue + ch.sendToQueue(q, Buffer.from(direct)); + return waitForMessages(q);}) + .then(function() {return ch.get(q)}) + .then(function(m) { + // the direct to queue message got through, the via-binding + // message (sent first) did not + assert.equal(direct, m.content.toString()); + }); +}); + +// To some extent this is now just testing semantics of the server, +// but we can at least try out a few settings, and consume. +chtest("consume via exchange-exchange binding", function(ch) { + var ex1 = 'test.ex-ex-binding1', ex2 = 'test.ex-ex-binding2'; + var q = 'test.ex-ex-binding-q'; + var rk = 'test.routing.key', msg = randomString(); + return Promise.join( + ch.assertExchange(ex1, 'direct', EX_OPTS), + ch.assertExchange(ex2, 'fanout', + {durable: false, internal: true}), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindExchange(ex2, ex1, rk, {}), + ch.bindQueue(q, ex2, '', {})) + .then(function() { + return new Promise(function(resolve, reject) { + function delivery(m) { + if (m.content.toString() === msg) resolve(); + else reject(new Error("Wrong message")); + } + ch.consume(q, delivery, {noAck: true}) + .then(function() { + ch.publish(ex1, rk, Buffer.from(msg)); + }); + }); + }); +}); + +// bind again, unbind, publish, get-empty +chtest("unbind exchange", function(ch) { + var source = 'test.unbind-ex-source'; + var dest = 'test.unbind-ex-dest'; + var q = 'test.unbind-ex-queue'; + var viabinding = randomString(); + var direct = randomString(); + + return Promise.join( + ch.assertExchange(source, 'fanout', EX_OPTS), + ch.assertExchange(dest, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindExchange(dest, source, '', {}), + ch.bindQueue(q, dest, '', {})) + .then(function() { + ch.publish(source, '', Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { // message got through! + return ch.get(q, {noAck:true}) + .then(function(m) {assert(m);});}) + .then(function() { + return ch.unbindExchange(dest, source, '', {});}) + .then(function() { + // via the no-longer-existing binding + ch.publish(source, '', Buffer.from(viabinding)); + // direct to the queue + ch.sendToQueue(q, Buffer.from(direct)); + return waitForMessages(q);}) + .then(function() {return ch.get(q)}) + .then(function(m) { + // the direct to queue message got through, the via-binding + // message (sent first) did not + assert.equal(direct, m.content.toString()); + }); +}); + +// This is a bit convoluted. Sorry. +chtest("cancel consumer", function(ch) { + var q = 'test.consumer-cancel'; + var ctag; + var recv1 = new Promise(function (resolve, reject) { + Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + // My callback is 'resolve the promise in `arrived`' + ch.consume(q, resolve, {noAck:true}) + .then(function(ok) { + ctag = ok.consumerTag; + ch.sendToQueue(q, Buffer.from('foo')); + })); + }); + + // A message should arrive because of the consume + return recv1.then(function() { + var recv2 = Promise.join( + ch.cancel(ctag).then(function() { + return ch.sendToQueue(q, Buffer.from('bar')); + }), + // but check a message did arrive in the queue + waitForMessages(q)) + .then(function() { + return ch.get(q, {noAck:true}); + }) + .then(function(m) { + // I'm going to reject it, because I flip succeed/fail + // just below + if (m.content.toString() === 'bar') { + throw new Error(); + } + }); + + return expectFail(recv2); + }); +}); + +chtest("cancelled consumer", function(ch) { + var q = 'test.cancelled-consumer'; + return new Promise(function(resolve, reject) { + return Promise.join( + ch.assertQueue(q), + ch.purgeQueue(q), + ch.consume(q, function(msg) { + if (msg === null) resolve(); + else reject(new Error('Message not expected')); + })) + .then(function() { + return ch.deleteQueue(q); + }); + }); +}); + +// ack, by default, removes a single message from the queue +chtest("ack", function(ch) { + var q = 'test.ack'; + var msg1 = randomString(), msg2 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + ch.sendToQueue(q, Buffer.from(msg2)); + return waitForMessages(q, 2); + }) + .then(function() { + return ch.get(q, {noAck: false}) + }) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.ack(m); + // %%% is there a race here? may depend on + // rabbitmq-sepcific semantics + return ch.get(q); + }) + .then(function(m) { + assert(m); + assert.equal(msg2, m.content.toString()); + }); +}); + +// Nack, by default, puts a message back on the queue (where in the +// queue is up to the server) +chtest("nack", function(ch) { + var q = 'test.nack'; + var msg1 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: false})}) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.nack(m); + return waitForMessages(q);}) + .then(function() { + return ch.get(q);}) + .then(function(m) { + assert(m); + assert.equal(msg1, m.content.toString()); + }); +}); + +// reject is a near-synonym for nack, the latter of which is not +// available in earlier RabbitMQ (or in AMQP proper). +chtest("reject", function(ch) { + var q = 'test.reject'; + var msg1 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: false})}) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.reject(m); + return waitForMessages(q);}) + .then(function() { + return ch.get(q);}) + .then(function(m) { + assert(m); + assert.equal(msg1, m.content.toString()); + }); +}); + +chtest("prefetch", function(ch) { + var q = 'test.prefetch'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), + ch.prefetch(1)) + .then(function() { + ch.sendToQueue(q, Buffer.from('foobar')); + ch.sendToQueue(q, Buffer.from('foobar')); + return waitForMessages(q, 2); + }) + .then(function() { + return new Promise(function(resolve) { + var messageCount = 0; + function receive(msg) { + ch.ack(msg); + if (++messageCount > 1) { + resolve(messageCount); + } + } + return ch.consume(q, receive, {noAck: false}) + }); + }) + .then(function(c) { + return assert.equal(2, c); + }); +}); + +chtest('close', function(ch) { + // Resolving promise guarantees + // channel is closed + return ch.close(); +}); + +}); + +var confirmtest = channel_test.bind(null, 'createConfirmChannel'); + +suite("confirms", function() { + +confirmtest('message is confirmed', function(ch) { + var q = 'test.confirm-message'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + return ch.sendToQueue(q, Buffer.from('bleep')); + }); +}); + +// Usually one can provoke the server into confirming more than one +// message in an ack by simply sending a few messages in quick +// succession; a bit unscientific I know. Luckily we can eavesdrop on +// the acknowledgements coming through to see if we really did get a +// multi-ack. +confirmtest('multiple confirms', function(ch) { + var q = 'test.multiple-confirms'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + var multipleRainbows = false; + ch.on('ack', function(a) { + if (a.multiple) multipleRainbows = true; + }); + + function prod(num) { + var cs = []; + + function sendAndPushPromise() { + var conf = Promise.fromCallback(function(cb) { + return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb); + }); + cs.push(conf); + } + + for (var i=0; i < num; i++) sendAndPushPromise(); + + return Promise.all(cs).then(function() { + if (multipleRainbows) return true; + else if (num > 500) throw new Error( + "Couldn't provoke the server" + + " into multi-acking with " + num + + " messages; giving up"); + else { + //console.warn("Failed with " + num + "; trying " + num * 2); + return prod(num * 2); + } + }); + } + return prod(5); + }); +}); + +confirmtest('wait for confirms', function(ch) { + for (var i=0; i < 1000; i++) { + ch.publish('', '', Buffer.from('foobar'), {}); + } + return ch.waitForConfirms(); +}) + +confirmtest('works when channel is closed', function(ch) { + for (var i=0; i < 1000; i++) { + ch.publish('', '', Buffer.from('foobar'), {}); + } + return ch.close().then(function () { + return ch.waitForConfirms() + }).then(function () { + assert.strictEqual(true, false, 'Wait should have failed.') + }, function (e) { + assert.strictEqual(e.message, 'channel closed') + }); +}); + +}); diff --git a/node_modules/amqplib/test/codec.js b/node_modules/amqplib/test/codec.js new file mode 100644 index 0000000..55a326f --- /dev/null +++ b/node_modules/amqplib/test/codec.js @@ -0,0 +1,238 @@ +'use strict'; + +var codec = require('../lib/codec'); +var defs = require('../lib/defs'); +var assert = require('assert'); +var ints = require('buffer-more-ints'); +var Buffer = require('safe-buffer').Buffer +var C = require('claire'); +var forAll = C.forAll; + +// These just test known encodings; to generate the answers I used +// RabbitMQ's binary generator module. + +var testCases = [ + // integers + ['byte', {byte: 112}, [4,98,121,116,101,98,112]], + ['byte max value', {byte: 127}, [4,98,121,116,101,98,127]], + ['byte min value', {byte: -128}, [4,98,121,116,101,98,128]], + ['< -128 promoted to signed short', {short: -129}, [5,115,104,111,114,116,115,255,127]], + ['> 127 promoted to short', {short: 128}, [5,115,104,111,114,116,115,0,128]], + ['< 2^15 still a short', {short: 0x7fff}, [5,115,104,111,114,116,115,127,255]], + ['-2^15 still a short', {short: -0x8000}, [5,115,104,111,114,116,115,128,0]], + ['>= 2^15 promoted to int', {int: 0x8000}, [3,105,110,116,73,0,0,128,0]], + ['< -2^15 promoted to int', {int: -0x8001}, [3,105,110,116,73,255,255,127,255]], + ['< 2^31 still an int', {int: 0x7fffffff}, [3,105,110,116,73,127,255,255,255]], + ['>= -2^31 still an int', {int: -0x80000000}, [3,105,110,116,73,128,0,0,0]], + ['>= 2^31 promoted to long', {long: 0x80000000}, [4,108,111,110,103,108,0,0,0,0,128,0,0,0]], + ['< -2^31 promoted to long', {long: -0x80000001}, [4,108,111,110,103,108,255,255,255,255,127,255,255,255]], + + // floating point + ['float value', {double: 0.5}, [6,100,111,117,98,108,101,100,63,224,0,0,0,0,0,0]], + ['negative float value', {double: -0.5}, [6,100,111,117,98,108,101,100,191,224,0,0,0,0,0,0]], + // %% test some boundaries of precision? + + // string + ['string', {string: "boop"}, [6,115,116,114,105,110,103,83,0,0,0,4,98,111,111,112]], + + // buffer -> byte array + ['byte array from buffer', {bytes: Buffer.from([1,2,3,4])}, + [5,98,121,116,101,115,120,0,0,0,4,1,2,3,4]], + + // boolean, void + ['true', {bool: true}, [4,98,111,111,108,116,1]], + ['false', {bool: false}, [4,98,111,111,108,116,0]], + ['null', {'void': null}, [4,118,111,105,100,86]], + + // array, object + ['array', {array: [6, true, "foo"]}, + [5,97,114,114,97,121,65,0,0,0,12,98,6,116,1,83,0,0,0,3,102,111,111]], + ['object', {object: {foo: "bar", baz: 12}}, + [6,111,98,106,101,99,116,70,0,0,0,18,3,102,111,111,83,0, + 0,0,3,98,97,114,3,98,97,122,98,12]], + + // exotic types + ['timestamp', {timestamp: {'!': 'timestamp', value: 1357212277527}}, + [9,116,105,109,101,115,116,97,109,112,84,0,0,1,60,0,39,219,23]], + ['decimal', {decimal: {'!': 'decimal', value: {digits: 2345, places: 2}}}, + [7,100,101,99,105,109,97,108,68,2,0,0,9,41]], + ['float', {float: {'!': 'float', value: 0.1}}, + [5,102,108,111,97,116,102,61,204,204,205]], +]; + +function bufferToArray(b) { + return Array.prototype.slice.call(b); +} + +suite("Implicit encodings", function() { + + testCases.forEach(function(tc) { + var name = tc[0], val = tc[1], expect = tc[2]; + test(name, function() { + var buffer = Buffer.alloc(1000); + var size = codec.encodeTable(buffer, val, 0); + var result = buffer.slice(4, size); + assert.deepEqual(expect, bufferToArray(result)); + }); + }); +}); + +// Whole frames + +var amqp = require('./data'); + +function roundtrip_table(t) { + var buf = Buffer.alloc(4096); + var size = codec.encodeTable(buf, t, 0); + var decoded = codec.decodeFields(buf.slice(4, size)); // ignore the length-prefix + try { + assert.deepEqual(removeExplicitTypes(t), decoded); + } + catch (e) { return false; } + return true; +} + +function roundtrips(T) { + return forAll(T).satisfy(function(v) { return roundtrip_table({value: v}); }); +} + +suite("Roundtrip values", function() { + [ + amqp.Octet, + amqp.ShortStr, + amqp.LongStr, + amqp.UShort, + amqp.ULong, + amqp.ULongLong, + amqp.UShort, + amqp.Short, + amqp.Long, + amqp.Bit, + amqp.Decimal, + amqp.Timestamp, + amqp.Double, + amqp.Float, + amqp.FieldArray, + amqp.FieldTable + ].forEach(function(T) { + test(T.toString() + ' roundtrip', roundtrips(T).asTest()); + }); +}); + +// When encoding, you can supply explicitly-typed fields like `{'!': +// int32, 50}`. Most of these do not appear in the decoded values, so +// to compare like-to-like we have to remove them from the input. +function removeExplicitTypes(input) { + switch (typeof input) { + case 'object': + if (input == null) { + return null; + } + if (Array.isArray(input)) { + var newArr = []; + for (var i = 0; i < input.length; i++) { + newArr[i] = removeExplicitTypes(input[i]); + } + return newArr; + } + if (Buffer.isBuffer(input)) { + return input; + } + switch (input['!']) { + case 'timestamp': + case 'decimal': + case 'float': + return input; + case undefined: + var newObj = {} + for (var k in input) { + newObj[k] = removeExplicitTypes(input[k]); + } + return newObj; + default: + return input.value; + } + + default: + return input; + } +} + +// Asserts that the decoded fields are equal to the original fields, +// or equal to a default where absent in the original. The defaults +// depend on the type of method or properties. +// +// This works slightly different for methods and properties: for +// methods, each field must have a value, so the default is +// substituted for undefined values when encoding; for properties, +// fields may be absent in the encoded value, so a default is +// substituted for missing fields when decoding. The effect is the +// same so far as these tests are concerned. +function assertEqualModuloDefaults(original, decodedFields) { + var args = defs.info(original.id).args; + for (var i=0; i < args.length; i++) { + var arg = args[i]; + var originalValue = original.fields[arg.name]; + var decodedValue = decodedFields[arg.name]; + try { + if (originalValue === undefined) { + // longstr gets special treatment here, since the defaults are + // given as strings rather than buffers, but the decoded values + // will be buffers. + assert.deepEqual((arg.type === 'longstr') ? + Buffer.from(arg.default) : arg.default, + decodedValue); + } + else { + assert.deepEqual(removeExplicitTypes(originalValue), decodedValue); + } + } + catch (assertionErr) { + var methodOrProps = defs.info(original.id).name; + assertionErr.message += ' (frame ' + methodOrProps + + ' field ' + arg.name + ')'; + throw assertionErr; + } + } + // %%% TODO make sure there's no surplus fields + return true; +} + +// This is handy for elsewhere +module.exports.assertEqualModuloDefaults = assertEqualModuloDefaults; + +function roundtripMethod(Method) { + return forAll(Method).satisfy(function(method) { + var buf = defs.encodeMethod(method.id, 0, method.fields); + // FIXME depends on framing, ugh + var fs1 = defs.decode(method.id, buf.slice(11, buf.length)); + assertEqualModuloDefaults(method, fs1); + return true; + }); +} + +function roundtripProperties(Properties) { + return forAll(Properties).satisfy(function(properties) { + var buf = defs.encodeProperties(properties.id, 0, properties.size, + properties.fields); + // FIXME depends on framing, ugh + var fs1 = defs.decode(properties.id, buf.slice(19, buf.length)); + assert.equal(properties.size, ints.readUInt64BE(buf, 11)); + assertEqualModuloDefaults(properties, fs1); + return true; + }); +} + +suite("Roundtrip methods", function() { + amqp.methods.forEach(function(Method) { + test(Method.toString() + ' roundtrip', + roundtripMethod(Method).asTest()); + }); +}); + +suite("Roundtrip properties", function() { + amqp.properties.forEach(function(Properties) { + test(Properties.toString() + ' roundtrip', + roundtripProperties(Properties).asTest()); + }); +}); diff --git a/node_modules/amqplib/test/connect.js b/node_modules/amqplib/test/connect.js new file mode 100644 index 0000000..ed4878b --- /dev/null +++ b/node_modules/amqplib/test/connect.js @@ -0,0 +1,152 @@ +'use strict'; + +var connect = require('../lib/connect').connect; +var Buffer = require('safe-buffer').Buffer +var credentialsFromUrl = require('../lib/connect').credentialsFromUrl; +var assert = require('assert'); +var util = require('./util'); +var net = require('net'); +var fail = util.fail, succeed = util.succeed, + kCallback = util.kCallback, + succeedIfAttributeEquals = util.succeedIfAttributeEquals; +var format = require('util').format; + +var URL = process.env.URL || 'amqp://localhost'; + +var urlparse = require('url-parse'); + +suite("Credentials", function() { + + function checkCreds(creds, user, pass, done) { + if (creds.mechanism != 'PLAIN') { + return done('expected mechanism PLAIN'); + } + if (creds.username != user || creds.password != pass) { + return done(format("expected '%s', '%s'; got '%s', '%s'", + user, pass, creds.username, creds.password)); + } + done(); + } + + test("no creds", function(done) { + var parts = urlparse('amqp://localhost'); + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'guest', 'guest', done); + }); + test("usual user:pass", function(done) { + var parts = urlparse('amqp://user:pass@localhost') + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'user', 'pass', done); + }); + test("missing user", function(done) { + var parts = urlparse('amqps://:password@localhost'); + var creds = credentialsFromUrl(parts); + checkCreds(creds, '', 'password', done); + }); + test("missing password", function(done) { + var parts = urlparse('amqps://username:@localhost'); + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'username', '', done); + }); + test("escaped colons", function(done) { + var parts = urlparse('amqp://user%3Aname:pass%3Aword@localhost') + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'user:name', 'pass:word', done); + }); +}); + +suite("Connect API", function() { + + test("Connection refused", function(done) { + connect('amqp://localhost:23450', {}, + kCallback(fail(done), succeed(done))); + }); + + // %% this ought to fail the promise, rather than throwing an error + test("bad URL", function() { + assert.throws(function() { + connect('blurble'); + }); + }); + + test("wrongly typed open option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var q = parts.query || {}; + q.frameMax = 'NOT A NUMBER'; + parts.query = q; + var u = url.format(parts); + connect(u, {}, kCallback(fail(done), succeed(done))); + }); + + test("serverProperties", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var config = parts.query || {}; + connect(config, {}, function(err, connection) { + if (err) { return done(err); } + assert.equal(connection.serverProperties.product, 'RabbitMQ'); + done(); + }); + }); + + test("using custom heartbeat option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var config = parts.query || {}; + config.heartbeat = 20; + connect(config, {}, kCallback(succeedIfAttributeEquals('heartbeat', 20, done), fail(done))); + }); + + test("wrongly typed heartbeat option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var config = parts.query || {}; + config.heartbeat = 'NOT A NUMBER'; + connect(config, {}, kCallback(fail(done), succeed(done))); + }); + + test("using plain credentials", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var u = 'guest', p = 'guest'; + if (parts.auth) { + var auth = parts.auth.split(":"); + u = auth[0], p = auth[1]; + } + connect(URL, {credentials: require('../lib/credentials').plain(u, p)}, + kCallback(succeed(done), fail(done))); + }); + + test("using amqplain credentials", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var u = 'guest', p = 'guest'; + if (parts.auth) { + var auth = parts.auth.split(":"); + u = auth[0], p = auth[1]; + } + connect(URL, {credentials: require('../lib/credentials').amqplain(u, p)}, + kCallback(succeed(done), fail(done))); + }); + + test("using unsupported mechanism", function(done) { + var creds = { + mechanism: 'UNSUPPORTED', + response: function() { return Buffer.from(''); } + }; + connect(URL, {credentials: creds}, + kCallback(fail(done), succeed(done))); + }); + + test("with a given connection timeout", function(done) { + var timeoutServer = net.createServer(function() {}).listen(31991); + + connect('amqp://localhost:31991', {timeout: 50}, function(err, val) { + timeoutServer.close(); + if (val) done(new Error('Expected connection timeout, did not')); + else done(); + }); + }); + +}); diff --git a/node_modules/amqplib/test/connection.js b/node_modules/amqplib/test/connection.js new file mode 100644 index 0000000..8b87c92 --- /dev/null +++ b/node_modules/amqplib/test/connection.js @@ -0,0 +1,391 @@ +'use strict'; + +var assert = require('assert'); +var defs = require('../lib/defs'); +var Buffer = require('safe-buffer').Buffer; +var Connection = require('../lib/connection').Connection; +var HEARTBEAT = require('../lib/frame').HEARTBEAT; +var HB_BUF = require('../lib/frame').HEARTBEAT_BUF; +var util = require('./util'); +var succeed = util.succeed, fail = util.fail, latch = util.latch; +var completes = util.completes; +var kCallback = util.kCallback; + +var LOG_ERRORS = process.env.LOG_ERRORS; + +var OPEN_OPTS = { + // start-ok + 'clientProperties': {}, + 'mechanism': 'PLAIN', + 'response': Buffer.from(['', 'guest', 'guest'].join(String.fromCharCode(0))), + 'locale': 'en_US', + + // tune-ok + 'channelMax': 0, + 'frameMax': 0, + 'heartbeat': 0, + + // open + 'virtualHost': '/', + 'capabilities': '', + 'insist': 0 +}; +module.exports.OPEN_OPTS = OPEN_OPTS; + +function happy_open(send, wait) { + // kick it off + send(defs.ConnectionStart, + {versionMajor: 0, + versionMinor: 9, + serverProperties: {}, + mechanisms: Buffer.from('PLAIN'), + locales: Buffer.from('en_US')}); + return wait(defs.ConnectionStartOk)() + .then(function(f) { + send(defs.ConnectionTune, + {channelMax: 0, + heartbeat: 0, + frameMax: 0}); + }) + .then(wait(defs.ConnectionTuneOk)) + .then(wait(defs.ConnectionOpen)) + .then(function(f) { + send(defs.ConnectionOpenOk, + {knownHosts: ''}); + }); +} +module.exports.connection_handshake = happy_open; + +function connectionTest(client, server) { + return function(done) { + var bothDone = latch(2, done); + var pair = util.socketPair(); + var c = new Connection(pair.client); + if (LOG_ERRORS) c.on('error', console.warn); + client(c, bothDone); + + // NB only not a race here because the writes are synchronous + var protocolHeader = pair.server.read(8); + assert.deepEqual(Buffer.from("AMQP" + String.fromCharCode(0,0,9,1)), + protocolHeader); + + var s = util.runServer(pair.server, function(send, wait) { + server(send, wait, bothDone, pair.server); + }); + }; +} + +suite("Connection errors", function() { + + test("socket close during open", function(done) { + // RabbitMQ itself will take at least 3 seconds to close the socket + // in the event of a handshake problem. Instead of using a live + // connection, I'm just going to pretend. + var pair = util.socketPair(); + var conn = new Connection(pair.client); + pair.server.on('readable', function() { + pair.server.end(); + }); + conn.open({}, kCallback(fail(done), succeed(done))); + }); + + test("bad frame during open", function(done) { + var ss = util.socketPair(); + var conn = new (require('../lib/connection').Connection)(ss.client); + ss.server.on('readable', function() { + ss.server.write(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); + }); + conn.open({}, kCallback(fail(done), succeed(done))); + }); + +}); + +suite("Connection open", function() { + +test("happy", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(succeed(done), fail(done))); + }, + function(send, wait, done) { + happy_open(send, wait).then(succeed(done), fail(done)); + })); + +test("wrong first frame", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function(send, wait, done) { + // bad server! bad! whatever were you thinking? + completes(function() { + send(defs.ConnectionTune, + {channelMax: 0, + heartbeat: 0, + frameMax: 0}); + }, done); + })); + +test("unexpected socket close", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function(send, wait, done, socket) { + send(defs.ConnectionStart, + {versionMajor: 0, + versionMinor: 9, + serverProperties: {}, + mechanisms: Buffer.from('PLAIN'), + locales: Buffer.from('en_US')}); + return wait(defs.ConnectionStartOk)() + .then(function() { + socket.end(); + }) + .then(succeed(done), fail(done)); + })); + +}); + +suite("Connection running", function() { + +test("wrong frame on channel 0", connectionTest( + function(c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(function() { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 0); + }) + .then(wait(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}, 0); + }).then(succeed(done), fail(done)); + })); + +test("unopened channel", connectionTest( + function(c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(function() { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 3); + }) + .then(wait(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}, 0); + }).then(succeed(done), fail(done)); + })); + +test("unexpected socket close", connectionTest( + function(c, done) { + var errorAndClosed = latch(2, done); + c.on('error', succeed(errorAndClosed)); + c.on('close', succeed(errorAndClosed)); + c.open(OPEN_OPTS, kCallback(function() { + c.sendHeartbeat(); + }, fail(errorAndClosed))); + }, + function(send, wait, done, socket) { + happy_open(send, wait) + .then(wait()) + .then(function() { + socket.end(); + }).then(succeed(done)); + })); + +test("connection.blocked", connectionTest( + function(c, done) { + c.on('blocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done, socket) { + happy_open(send, wait) + .then(function() { + send(defs.ConnectionBlocked, {reason: 'felt like it'}, 0); + }) + .then(succeed(done)); + })); + +test("connection.unblocked", connectionTest( + function(c, done) { + c.on('unblocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done, socket) { + happy_open(send, wait) + .then(function() { + send(defs.ConnectionUnblocked, {}, 0); + }) + .then(succeed(done)); + })); + + +}); + +suite("Connection close", function() { + +test("happy", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open(OPEN_OPTS, kCallback(function(_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, function() {})); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +test("interleaved close frames", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open(OPEN_OPTS, kCallback(function(_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, done)); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Ha!", + replyCode: defs.constants.REPLY_SUCCESS, + methodId: 0, classId: 0 + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(function(f) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +test("server error close", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', succeed(done)); + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Begone", + replyCode: defs.constants.INTERNAL_ERROR, + methodId: 0, classId: 0 + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + +test("operator-intiated close", connectionTest( + function(c, done) { + c.on('close', succeed(done)); + c.on('error', fail(done)); + c.open(OPEN_OPTS); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Begone", + replyCode: defs.constants.CONNECTION_FORCED, + methodId: 0, classId: 0 + }); + }) + .then(wait(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + + +test("double close", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(function() { + c.close(); + // NB no synchronisation, we do this straight away + assert.throws(function() { + c.close(); + }); + done(); + }, done)); + }, + function(send, wait, done) { + happy_open(send, wait) + .then(wait(defs.ConnectionClose)) + .then(function() { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +}); + +suite("heartbeats", function() { + +var heartbeat = require('../lib/heartbeat'); + +setup(function() { + heartbeat.UNITS_TO_MS = 20; +}); + +teardown(function() { + heartbeat.UNITS_TO_MS = 1000; +}); + +test("send heartbeat after open", connectionTest( + function(c, done) { + completes(function() { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + // Don't leave the error waiting to happen for the next test, this + // confuses mocha awfully + c.on('error', function() {}); + c.open(opts); + }, done); + }, + function(send, wait, done, socket) { + var timer; + happy_open(send, wait) + .then(function() { + timer = setInterval(function() { + socket.write(HB_BUF); + }, heartbeat.UNITS_TO_MS); + }) + .then(wait()) + .then(function(hb) { + if (hb === HEARTBEAT) done(); + else done("Next frame after silence not a heartbeat"); + clearInterval(timer); + }); + })); + +test("detect lack of heartbeats", connectionTest( + function(c, done) { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + c.on('error', succeed(done)); + c.open(opts); + }, + function(send, wait, done, socket) { + happy_open(send, wait) + .then(succeed(done), fail(done)); + // conspicuously not sending anything ... + })); + +}); diff --git a/node_modules/amqplib/test/data.js b/node_modules/amqplib/test/data.js new file mode 100644 index 0000000..2fa9bf0 --- /dev/null +++ b/node_modules/amqplib/test/data.js @@ -0,0 +1,255 @@ +// Property-based testing representations of various things in AMQP + +'use strict'; + +var C = require('claire'); +var Buffer = require('safe-buffer').Buffer; +var forAll = C.forAll; +var arb = C.data; +var transform = C.transform; +var repeat = C.repeat; +var label = C.label; +var sequence = C.sequence; +var asGenerator = C.asGenerator; +var sized = C.sized; +var recursive = C.recursive; +var choice = C.choice; +var Undefined = C.Undefined; + +// Stub these out so we can use outside tests +// if (!suite) var suite = function() {} +// if (!test) var test = function() {} + +// These aren't exported in claire/index. so I could have to reproduce +// them I guess. +function choose(a, b) { + return Math.random() * (b - a) + a; +} + +function chooseInt(a, b) { + return Math.floor(choose(a, b)); +} + +function rangeInt(name, a, b) { + return label(name, + asGenerator(function(_) { return chooseInt(a, b); })); +} + +function toFloat32(i) { + var b = Buffer.alloc(4); + b.writeFloatBE(i, 0); + return b.readFloatBE(0); +} + +function floatChooser(maxExp) { + return function() { + var n = Number.NaN; + while (isNaN(n)) { + var mantissa = Math.random() * 2 - 1; + var exponent = chooseInt(0, maxExp); + n = Math.pow(mantissa, exponent); + } + return n; + } +} + +function explicitType(t, underlying) { + return label(t, transform(function(n) { + return {'!': t, value: n}; + }, underlying)); +} + +// FIXME null, byte array, others? + +var Octet = rangeInt('octet', 0, 255); +var ShortStr = label('shortstr', + transform(function(s) { + return s.substr(0, 255); + }, arb.Str)); + +var LongStr = label('longstr', + transform( + function(bytes) { return Buffer.from(bytes); }, + repeat(Octet))); + +var UShort = rangeInt('short-uint', 0, 0xffff); +var ULong = rangeInt('long-uint', 0, 0xffffffff); +var ULongLong = rangeInt('longlong-uint', 0, 0xffffffffffffffff); +var Short = rangeInt('short-int', -0x8000, 0x7fff); +var Long = rangeInt('long-int', -0x80000000, 0x7fffffff); +var LongLong = rangeInt('longlong-int', -0x8000000000000000, + 0x7fffffffffffffff); +var Bit = label('bit', arb.Bool); +var Double = label('double', asGenerator(floatChooser(308))); +var Float = label('float', transform(toFloat32, floatChooser(38))); +var Timestamp = label('timestamp', transform( + function(n) { + return {'!': 'timestamp', value: n}; + }, ULongLong)); +var Decimal = label('decimal', transform( + function(args) { + return {'!': 'decimal', value: {places: args[1], digits: args[0]}}; + }, sequence(arb.UInt, Octet))); + +// Signed 8 bit int +var Byte = rangeInt('byte', -128, 127); + +// Explicitly typed values +var ExByte = explicitType('byte', Byte); +var ExInt8 = explicitType('int8', Byte); +var ExShort = explicitType('short', Short); +var ExInt16 = explicitType('int16', Short); +var ExInt = explicitType('int', Long); +var ExInt32 = explicitType('int32', Long); +var ExLong = explicitType('long', LongLong); +var ExInt64 = explicitType('int64', LongLong); + +var FieldArray = label('field-array', recursive(function() { + return arb.Array( + arb.Null, + LongStr, ShortStr, + Octet, UShort, ULong, ULongLong, + Byte, Short, Long, LongLong, + ExByte, ExInt8, ExShort, ExInt16, + ExInt, ExInt32, ExLong, ExInt64, + Bit, Float, Double, FieldTable, FieldArray) +})); + +var FieldTable = label('table', recursive(function() { + return sized(function() { return 5; }, + arb.Object( + arb.Null, + LongStr, ShortStr, Octet, + UShort, ULong, ULongLong, + Byte, Short, Long, LongLong, + ExByte, ExInt8, ExShort, ExInt16, + ExInt, ExInt32, ExLong, ExInt64, + Bit, Float, Double, FieldArray, FieldTable)) +})); + +// Internal tests of our properties +var domainProps = [ + [Octet, function(n) { return n >= 0 && n < 256; }], + [ShortStr, function(s) { return typeof s === 'string' && s.length < 256; }], + [LongStr, function(s) { return Buffer.isBuffer(s); }], + [UShort, function(n) { return n >= 0 && n <= 0xffff; }], + [ULong, function(n) { return n >= 0 && n <= 0xffffffff; }], + [ULongLong, function(n) { + return n >= 0 && n <= 0xffffffffffffffff; }], + [Short, function(n) { return n >= -0x8000 && n <= 0x8000; }], + [Long, function(n) { return n >= -0x80000000 && n < 0x80000000; }], + [LongLong, function(n) { return n >= -0x8000000000000000 && n < 0x8000000000000000; }], + [Bit, function(b) { return typeof b === 'boolean'; }], + [Double, function(f) { return !isNaN(f) && isFinite(f); }], + [Float, function(f) { return !isNaN(f) && isFinite(f) && (Math.log(Math.abs(f)) * Math.LOG10E) < 309; }], + [Decimal, function(d) { + return d['!'] === 'decimal' && + d.value['places'] <= 255 && + d.value['digits'] <= 0xffffffff; + }], + [Timestamp, function(t) { return t['!'] === 'timestamp'; }], + [FieldTable, function(t) { return typeof t === 'object'; }], + [FieldArray, function(a) { return Array.isArray(a); }] +]; + +suite("Domains", function() { + domainProps.forEach(function(p) { + test(p[0] + ' domain', + forAll(p[0]).satisfy(p[1]).asTest({times: 500})); + }); +}); + +// For methods and properties (as opposed to field table values) it's +// easier just to accept and produce numbers for timestamps. +var ArgTimestamp = label('timestamp', ULongLong); + +// These are the domains used in method arguments +var ARG_TYPES = { + 'octet': Octet, + 'shortstr': ShortStr, + 'longstr': LongStr, + 'short': UShort, + 'long': ULong, + 'longlong': ULongLong, + 'bit': Bit, + 'table': FieldTable, + 'timestamp': ArgTimestamp +}; + +function argtype(thing) { + if (thing.default === undefined) { + return ARG_TYPES[thing.type]; + } + else { + return choice(ARG_TYPES[thing.type], Undefined); + } +} + +function zipObject(vals, names) { + var obj = {}; + vals.forEach(function(v, i) { obj[names[i]] = v; }); + return obj; +} + +function name(arg) { return arg.name; } + +var defs = require('../lib/defs'); + +function method(info) { + var domain = sequence.apply(null, info.args.map(argtype)); + var names = info.args.map(name); + return label(info.name, transform(function(fieldVals) { + return {id: info.id, + fields: zipObject(fieldVals, names)}; + }, domain)); +} + +function properties(info) { + var types = info.args.map(argtype); + types.unshift(ULongLong); // size + var domain = sequence.apply(null, types); + var names = info.args.map(name); + return label(info.name, transform(function(fieldVals) { + return {id: info.id, + size: fieldVals[0], + fields: zipObject(fieldVals.slice(1), names)}; + }, domain)); +} + +var methods = []; +var propertieses = []; + +for (var k in defs) { + if (k.substr(0, 10) === 'methodInfo') { + methods.push(method(defs[k])); + methods[defs[k].name] = method(defs[k]); + } + else if (k.substr(0, 14) === 'propertiesInfo') { + propertieses.push(properties(defs[k])); + propertieses[defs[k].name] = properties(defs[k]); + } +}; + +module.exports = { + Octet: Octet, + ShortStr: ShortStr, + LongStr: LongStr, + UShort: UShort, + ULong: ULong, + ULongLong: ULongLong, + Short: Short, + Long: Long, + LongLong: LongLong, + Bit: Bit, + Double: Double, + Float: Float, + Timestamp: Timestamp, + Decimal: Decimal, + FieldArray: FieldArray, + FieldTable: FieldTable, + + methods: methods, + properties: propertieses +}; + +module.exports.rangeInt = rangeInt; diff --git a/node_modules/amqplib/test/frame.js b/node_modules/amqplib/test/frame.js new file mode 100644 index 0000000..9b47f95 --- /dev/null +++ b/node_modules/amqplib/test/frame.js @@ -0,0 +1,199 @@ +'use strict'; + +var assert = require('assert'); +var succeed = require('./util').succeed; +var fail = require('./util').fail; +var Buffer = require('safe-buffer').Buffer; +var connection = require('../lib/connection'); +var Frames = connection.Connection; +var HEARTBEAT = require('../lib/frame').HEARTBEAT; +var Stream = require('stream'); +var PassThrough = Stream.PassThrough || + require('readable-stream/passthrough'); + +var defs = require('../lib/defs'); + +// We'll need to supply a stream which we manipulate ourselves + +function inputs() { + // don't coalesce buffers, since that could mess up properties + // (e.g., encoded frame size) + return new PassThrough({objectMode: true}); +} + +var HB = Buffer.from([defs.constants.FRAME_HEARTBEAT, + 0, 0, // channel 0 + 0, 0, 0, 0, // zero size + defs.constants.FRAME_END]); + +suite("Explicit parsing", function() { + + test('Parse heartbeat', function() { + var input = inputs(); + var frames = new Frames(input); + input.write(HB); + assert(frames.recvFrame() === HEARTBEAT); + assert(!frames.recvFrame()); + }); + + test('Parse partitioned', function() { + var input = inputs(); + var frames = new Frames(input); + input.write(HB.slice(0, 3)); + assert(!frames.recvFrame()); + input.write(HB.slice(3)); + assert(frames.recvFrame() === HEARTBEAT); + assert(!frames.recvFrame()); + }); + + function testBogusFrame(name, bytes) { + test(name, function(done) { + var input = inputs(); + var frames = new Frames(input); + frames.frameMax = 5; //for the max frame test + input.write(Buffer.from(bytes)); + frames.step(function(err, frame) { + if (err != null) done(); + else done(new Error('Was a bogus frame!')); + }); + }); + } + + testBogusFrame('Wrong sized frame', + [defs.constants.FRAME_BODY, + 0,0, 0,0,0,0, // zero length + 65, // but a byte! + defs.constants.FRAME_END]); + + testBogusFrame('Unknown method frame', + [defs.constants.FRAME_METHOD, + 0,0, 0,0,0,4, + 0,0,0,0, // garbage ID + defs.constants.FRAME_END]); + + testBogusFrame('> max frame', + [defs.constants.FRAME_BODY, + 0,0, 0,0,0,6, // too big! + 65,66,67,68,69,70, + defs.constants.FRAME_END]); + +}); + +// Now for a bit more fun. + +var amqp = require('./data'); +var claire = require('claire'); +var choice = claire.choice; +var forAll = claire.forAll; +var repeat = claire.repeat; +var label = claire.label; +var sequence = claire.sequence; +var transform = claire.transform; +var sized = claire.sized; + +var assertEqualModuloDefaults = + require('./codec').assertEqualModuloDefaults; + +var Trace = label('frame trace', + repeat(choice.apply(choice, amqp.methods))); + +suite("Parsing", function() { + + function testPartitioning(partition) { + return forAll(Trace).satisfy(function(t) { + var bufs = []; + var input = inputs(); + var frames = new Frames(input); + var i = 0, ex; + frames.accept = function(f) { + // A minor hack to make sure we get the assertion exception; + // otherwise, it's just a test that we reached the line + // incrementing `i` for each frame. + try { + assertEqualModuloDefaults(t[i], f.fields); + } + catch (e) { + ex = e; + } + i++; + }; + + t.forEach(function(f) { + f.channel = 0; + bufs.push(defs.encodeMethod(f.id, 0, f.fields)); + }); + + partition(bufs).forEach(function (chunk) { input.write(chunk); }); + frames.acceptLoop(); + if (ex) throw ex; + return i === t.length; + }).asTest({times: 20}) + }; + + test("Parse trace of methods", + testPartitioning(function(bufs) { return bufs; })); + + test("Parse concat'd methods", + testPartitioning(function(bufs) { + return [Buffer.concat(bufs)]; + })); + + test("Parse partitioned methods", + testPartitioning(function(bufs) { + var full = Buffer.concat(bufs); + var onethird = Math.floor(full.length / 3); + var twothirds = 2 * onethird; + return [ + full.slice(0, onethird), + full.slice(onethird, twothirds), + full.slice(twothirds) + ]; + })); +}); + +var FRAME_MAX_MAX = 4096 * 4; +var FRAME_MAX_MIN = 4096; + +var FrameMax = amqp.rangeInt('frame max', + FRAME_MAX_MIN, + FRAME_MAX_MAX); + +var Body = sized(function(_n) { + return Math.floor(Math.random() * FRAME_MAX_MAX); +}, repeat(amqp.Octet)); + +var Content = transform(function(args) { + return { + method: args[0].fields, + header: args[1].fields, + body: Buffer.from(args[2]) + } +}, sequence(amqp.methods['BasicDeliver'], + amqp.properties['BasicProperties'], Body)); + +suite("Content framing", function() { + test("Adhere to frame max", + forAll(Content, FrameMax).satisfy(function(content, max) { + var input = inputs(); + var frames = new Frames(input); + frames.frameMax = max; + frames.sendMessage( + 0, + defs.BasicDeliver, content.method, + defs.BasicProperties, content.header, + content.body); + var f, i = 0, largest = 0; + while (f = input.read()) { + i++; + if (f.length > largest) largest = f.length; + if (f.length > max) { + return false; + } + } + // The ratio of frames to 'contents' should always be >= 2 + // (one properties frame and at least one content frame); > 2 + // indicates fragmentation. The largest is always, of course <= frame max + //console.log('Frames: %d; frames per message: %d; largest frame %d', i, i / t.length, largest); + return true; + }).asTest()); +}); diff --git a/node_modules/amqplib/test/mux.js b/node_modules/amqplib/test/mux.js new file mode 100644 index 0000000..b785ac0 --- /dev/null +++ b/node_modules/amqplib/test/mux.js @@ -0,0 +1,204 @@ +'use strict'; + +var assert = require('assert'); +var Mux = require('../lib/mux').Mux; +var PassThrough = require('stream').PassThrough || + require('readable-stream/passthrough'); + +var latch = require('./util').latch; +var schedule = require('./util').schedule; + +function stream() { + return new PassThrough({objectMode: true}); +} + +function readAllObjects(s, cb) { + var objs = []; + + function read() { + var v = s.read(); + while (v !== null) { + objs.push(v); + v = s.read(); + } + } + + s.on('end', function() { cb(objs); }); + s.on('readable', read); + + read(); +} + +test("single input", function(done) { + var input = stream(); + var output = stream(); + input.on('end', function() { output.end() }); + + var mux = new Mux(output); + mux.pipeFrom(input); + + var data = [1,2,3,4,5,6,7,8,9]; + // not 0, it's treated specially by PassThrough for some reason. By + // 'specially' I mean it breaks the stream. See e.g., + // https://github.com/isaacs/readable-stream/pull/55 + data.forEach(function (chunk) { input.write(chunk); }); + + readAllObjects(output, function(vals) { + assert.deepEqual(data, vals); + done(); + }); + + input.end(); +}); + +test("single input, resuming stream", function(done) { + var input = stream(); + var output = stream(); + input.on('end', function() { output.end() }); + + var mux = new Mux(output); + mux.pipeFrom(input); + + // Streams might be blocked and become readable again, simulate this + // using a special read function and a marker + var data = [1,2,3,4,'skip',6,7,8,9]; + + var oldRead = input.read; + input.read = function(size) { + var val = oldRead.call(input, size) + + if (val === 'skip') { + input.emit('readable'); + return null + } + + return val; + } + + data.forEach(function (chunk) { input.write(chunk); }); + + readAllObjects(output, function(vals) { + assert.deepEqual([1,2,3,4,6,7,8,9], vals); + done(); + }); + + input.end(); +}); + +test("two sequential inputs", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var data = [1,2,3,4,5,6,7,8,9]; + data.forEach(function(v) { input1.write(v); }); + + input1.on('end', function() { + data.forEach(function (v) { input2.write(v); }); + input2.end(); + }); + input2.on('end', function() { output.end(); }); + + input1.end(); + readAllObjects(output, function(vs) { + assert.equal(2 * data.length, vs.length); + done(); + }); +}); + +test("two interleaved inputs", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var endLatch = latch(2, function() { output.end(); }); + input1.on('end', endLatch); + input2.on('end', endLatch); + + var data = [1,2,3,4,5,6,7,8,9]; + data.forEach(function(v) { input1.write(v); }); + input1.end(); + + data.forEach(function(v) { input2.write(v); }); + input2.end(); + + readAllObjects(output, function(vs) { + assert.equal(2 * data.length, vs.length); + done(); + }); +}); + +test("unpipe", function(done) { + var input = stream(); + var output = stream(); + var mux = new Mux(output); + + var pipedData = [1,2,3,4,5]; + var unpipedData = [6,7,8,9]; + + mux.pipeFrom(input); + + schedule(function() { + pipedData.forEach(function (chunk) { input.write(chunk); }); + + schedule(function() { + mux.unpipeFrom(input); + + schedule(function() { + unpipedData.forEach(function(chunk) { input.write(chunk); }); + input.end(); + schedule(function() { + // exhaust so that 'end' fires + var v; while (v = input.read()); + }); + }); + }); + + }); + + input.on('end', function() { + output.end(); + }); + + readAllObjects(output, function(vals) { + try { + assert.deepEqual(pipedData, vals); + done(); + } + catch (e) { done(e); } + }); +}); + +test("roundrobin", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var endLatch = latch(2, function() { output.end(); }); + input1.on('end', endLatch); + input2.on('end', endLatch); + + var ones = [1,1,1,1,1]; + ones.forEach(function(v) { input1.write(v); }); + input1.end(); + + var twos = [2,2,2,2,2]; + twos.forEach(function(v) { input2.write(v); }); + input2.end(); + + readAllObjects(output, function(vs) { + assert.deepEqual([1,2,1,2,1,2,1,2,1,2], vs); + done(); + }); + +}); diff --git a/node_modules/amqplib/test/util.js b/node_modules/amqplib/test/util.js new file mode 100644 index 0000000..a41a8eb --- /dev/null +++ b/node_modules/amqplib/test/util.js @@ -0,0 +1,220 @@ +'use strict'; + +var Promise = require('bluebird'); +var crypto = require('crypto'); +var Connection = require('../lib/connection').Connection; +var PassThrough = + require('stream').PassThrough || + require('readable-stream/passthrough'); +var defs = require('../lib/defs'); +var assert = require('assert'); + +var schedule = (typeof setImmediate === 'function') ? + setImmediate : process.nextTick; + +function randomString() { + var hash = crypto.createHash('sha1'); + hash.update(crypto.randomBytes(64)); + return hash.digest('base64'); +} + + +// Set up a socket pair {client, server}, such that writes to the +// client are readable from the server, and writes to the server are +// readable at the client. +// +// +---+ +---+ +// | C | | S | +// --write->| l |----->| e |--read--> +// | i | | r | +// <--read--| e |<-----| v |<-write-- +// | n | | e | +// | t | | r | +// +---+ +---+ +// +// I also need to make sure that end called on either socket affects +// the other. + +function socketPair() { + var server = new PassThrough(); + var client = new PassThrough(); + server.write = client.push.bind(client); + client.write = server.push.bind(server); + function end(chunk, encoding) { + if (chunk) this.push(chunk, encoding); + this.push(null); + } + server.end = end.bind(client); + client.end = end.bind(server); + + return {client: client, server: server}; +} + +function runServer(socket, run) { + var frames = new Connection(socket); + // We will be closing the socket without doing a closing handshake, + // so cheat + frames.expectSocketClose = true; + // We also need to create some channel buffers, again a cheat + frames.freshChannel(null); + frames.freshChannel(null); + frames.freshChannel(null); + + function send(id, fields, channel, content) { + channel = channel || 0; + if (content) { + schedule(function() { + frames.sendMessage(channel, id, fields, + defs.BasicProperties, fields, + content); + }); + } + else { + schedule(function() { + frames.sendMethod(channel, id, fields); + }); + } + } + + function wait(method) { + return function() { + return new Promise(function(resolve, reject) { + if (method) { + frames.step(function(e, f) { + if (e !== null) return reject(e); + if (f.id === method) + resolve(f); + else + reject(new Error("Expected method: " + method + + ", got " + f.id)); + }); + } + else { + frames.step(function(e, f) { + if (e !== null) return reject(e); + else resolve(f); + }); + } + }); + }; + } + run(send, wait); + return frames; +} + +// Produce a callback that will complete the test successfully +function succeed(done) { + return function() { done(); } +} + +// Produce a callback that will complete the test successfully +// only if the value is an object, it has the specified +// attribute, and its value is equals to the expected value +function succeedIfAttributeEquals(attribute, value, done) { + return function(object) { + if (object && !(object instanceof Error) && value === object[attribute]) { + return done(); + } + + done(new Error(attribute + " is not equal to " + value)); + }; +} + +// Produce a callback that will fail the test, given either an error +// (to be used as a failure continuation) or any other value (to be +// used as a success continuation when failure is expected) +function fail(done) { + return function(err) { + if (err instanceof Error) done(err); + else done(new Error("Expected to fail, instead got " + err.toString())); + } +} + +// Create a function that will call done once it's been called itself +// `count` times. If it's called with an error value, it will +// immediately call done with that error value. +function latch(count, done) { + var awaiting = count; + var alive = true; + return function(err) { + if (err instanceof Error && alive) { + alive = false; + done(err); + } + else { + awaiting--; + if (awaiting === 0 && alive) { + alive = false; + done(); + } + } + }; +} + +// Call a thunk with a continuation that will be called with an error +// if the thunk throws one, or nothing if it runs to completion. +function completes(thunk, done) { + try { + thunk(); + done(); + } + catch (e) { done(e); } +} + +// Construct a Node.JS-style callback from a success continuation and +// an error continuation +function kCallback(k, ek) { + return function(err, val) { + if (err === null) k && k(val); + else ek && ek(err); + }; +} + +// A noddy way to make tests depend on the node version. +function versionGreaterThan(actual, spec) { + + function int(e) { return parseInt(e); } + + var version = actual.split('.').map(int); + var desired = spec.split('.').map(int); + for (var i=0; i < desired.length; i++) { + var a = version[i], b = desired[i]; + if (a != b) return a > b; + } + return false; +} + +suite('versionGreaterThan', function() { + +test('full spec', function() { + assert(versionGreaterThan('0.8.26', '0.6.12')); + assert(versionGreaterThan('0.8.26', '0.8.21')); +}); + +test('partial spec', function() { + assert(versionGreaterThan('0.9.12', '0.8')); +}); + +test('not greater', function() { + assert(!versionGreaterThan('0.8.12', '0.8.26')); + assert(!versionGreaterThan('0.6.2', '0.6.12')); + assert(!versionGreaterThan('0.8.29', '0.8')); +}); + +test + +}); + +module.exports = { + socketPair: socketPair, + runServer: runServer, + succeed: succeed, + succeedIfAttributeEquals: succeedIfAttributeEquals, + fail: fail, + latch: latch, + completes: completes, + kCallback: kCallback, + schedule: schedule, + randomString: randomString, + versionGreaterThan: versionGreaterThan +}; diff --git a/node_modules/bitsyntax/.travis.yml b/node_modules/bitsyntax/.travis.yml new file mode 100644 index 0000000..994efa2 --- /dev/null +++ b/node_modules/bitsyntax/.travis.yml @@ -0,0 +1,12 @@ +language: node_js + +node_js: + - "0.8" + - "0.10" + - "0.12" + - "4.2" + - "6.12" + - "8.9" + - "9.11" + - "10.10" + - "node" diff --git a/node_modules/bitsyntax/LICENSE b/node_modules/bitsyntax/LICENSE new file mode 100644 index 0000000..7d411ef --- /dev/null +++ b/node_modules/bitsyntax/LICENSE @@ -0,0 +1,6 @@ +bitsyntax-js copyright (c) 2012-2014 + Michael Bridgen + +This package, "bitsyntax-js", is licensed under the MIT License. A +copy may be found in the file LICENSE-MIT in this directory, or +downloaded from http://opensource.org/licenses/MIT. diff --git a/node_modules/bitsyntax/LICENSE-MIT b/node_modules/bitsyntax/LICENSE-MIT new file mode 100644 index 0000000..cde52c5 --- /dev/null +++ b/node_modules/bitsyntax/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2014 Michael Bridgen + +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/bitsyntax/Makefile b/node_modules/bitsyntax/Makefile new file mode 100644 index 0000000..ee27ab8 --- /dev/null +++ b/node_modules/bitsyntax/Makefile @@ -0,0 +1,15 @@ +.PHONY: test all + +GRAMMAR=lib/grammar.pegjs +PEGJS=./node_modules/.bin/pegjs + +all: lib/parser.js + +lib/parser.js: $(PEGJS) + $(PEGJS) $(GRAMMAR) $@ + +$(PEGJS): + npm install + +test: lib/parser.js + ./node_modules/.bin/mocha --check-leaks -R list -u tdd test/*.js diff --git a/node_modules/bitsyntax/README.md b/node_modules/bitsyntax/README.md new file mode 100644 index 0000000..02eed9b --- /dev/null +++ b/node_modules/bitsyntax/README.md @@ -0,0 +1,306 @@ +# Byte-wise matching for Node.JS + +[![Build Status](https://travis-ci.org/squaremo/bitsyntax-js.png?branch=master)](https://travis-ci.org/squaremo/bitsyntax-js) + +Gives a compact syntax for parsing and constructing byte buffers, +derived from [Erlang's bit +syntax](http://www.erlang.org/doc/programming_examples/bit_syntax.html#id64858). + +```js +var bitsyntax = require('bitsyntax'); +var pattern = bitsyntax.matcher('len:8/integer, str:len/binary'); +var bound = pattern(new Buffer([4, 0x41, 0x42, 0x43, 0x44])); +bound.str +// => +``` + +A typical use of this is parsing byte streams from sockets. For +example, size-prefixed frames: + +```js +var framePattern = bitsyntax.matcher('len:32/integer, frame:len/binary, rest/binary'); +socket.on('data', function process(data) { + var m; + if (m = framePattern(data)) { + emit('frame', m.frame); + process(m.rest); + } + else { + stashForNextData(data); + } +}); +``` + +Patterns can also be used to construct byte buffers from supplied +values: + +```js +var spdyDataFrame = require('bitsyntax') + .builder('streamId:32, flags:8, length:24, data/binary'); + +spdyDataFrame({streamId:5, flags:0, length:bin.length, data:bin}); +``` + +One or more segments of a pattern may also be supplied in multiple +arguments, if that is more convenient; this makes it easier to split a +long pattern over lines: + +```js +var p = bitsyntax.matcher('size:8, payload:size/binary', + 'rest/binary'); +``` + +## API + +### `matcher` + +Compiles a pattern as a string (or strings), to a function that will +return either a map of bindings, or `false`, given a buffer and +optionally an environment. The environment contains values for bound +variables in the pattern (if there are any). + +```js +var p = bitsyntax.matcher('header:headerSize/binary, rest/binary'); +var b = p(new Buffer([1, 2, 3, 4, 5]), {headerSize: 3}); +b.header +// => +``` + +A matcher will return `false` if the supplied buffer does not match +the pattern; for example, if it has too few bytes, or a literal is not +present. + +```js +var p = bitsyntax.matcher('"foo=", str/binary'); +p(new Buffer("bar=humbug")); +// => false +``` + +### `parse` and `match` + +When composed, equivalent to `matcher`; may be useful if you want to +examine the internal structure of patterns. + +`parse` takes strings as for `matcher`, and returns the internal +representation of the pattern. `match` takes this representation, a +buffer, and optionally an environment, and returns the bindings or +`false` (as with `matcher`). + +```js +var p = bitsyntax.parse('header:headerSize/binary', + 'rest/binary'); +var b = bitsyntax.match(p, new Buffer([1, 2, 3, 4, 5]), + {headerSize: 3}); +b.header +// => +``` + +### `builder` + +Takes a pattern and returns a function that will construct a byte +buffer, given values for the variables mentioned in the pattern. + +```js +var cons = bitsyntax.builder('size:8, bin/binary'); +cons({size:6, bin:new Buffer('foobar')}); +// => +``` + +Patterns supplied to builders are slightly different to patterns +supplied for matching, as noted below. + +### `build` + +Takes a parsed pattern and a map of variable values, and returns a +buffer. As with `match`, may be useful to debug patterns. + +```js +var pattern = bitsyntax.parse('size:8, bin:size/binary'); +bitsyntax.build(pattern, {size:6, bin: new Buffer('foobar')}); +// => +``` + +### `write` + +Writes variable values into a buffer, at an offset, according to the +parsed pattern given. Returns the finishing offset, i.e., the supplied +offset plus the number of bytes written. + +```js +var pattern = bitsyntax.parse('size:8, bin/binary'); +var buf = new Buffer(7); +bitsyntax.write(buf, 0, pattern, + {size:6, bin: new Buffer('foobar')}); +// => 7 +buf +// => +``` + +## Patterns + +Patterns are sequences of segments, each matching a value. Segments +have the general form + + value:size/type_specifier_list + +The size and type specifier list may be omitted, giving three extra +variations: + + value + value:size + value/type_specifier_list + +The type specifier list is a list of keywords separated by +hyphens. Type specifiers are described below. + +Patterns are generally supplied as strings, with a comma-separated +series of segments. + +### Variable or value + +The first part of a segment gives a variable name or a literal +value. If a variable name is given, the value matched by the segment +will be bound to that variable name for the rest of the pattern. If a +literal value is given, the matched value must equal that value. If a +variable's value is given in the environment, the matched value must +equal the provided value. + +When used in a builder, the literal value will be copied into the +buffer according to the type it is given. A variable name indicates a +slot into which a value supplied to the builder will be copied. + +The special variable name `_` discards the value matched; i.e., it +simply skips over the appropriate number of bits in the input. '_' is +not allowed in builder patterns. + +### Size and unit + +The size of a segment is given following the value or variable, +separated with a colon: + + foo:32 + +The unit is given in the list of specifiers as `'unit' and +an integer from 0..256, separated by a colon: + + foo:4/integer-unit:8 + +The size is the number of units in the value; the unit is given as a +number of bits. Unit can be of use, for example, when you want to +match integers of a number of bytes rather than a number of bits. + +For integers and floats, the default unit is 1 bit; to keep things +aligned on byte boundaries, `unit * size` must currently be a multiple +of 8. For binaries the default unit is 8, and the unit must be a +multiple of 8. + +If the size is omitted and the type is integer, the size defaults to +8. If the size is omitted and the type is binary, the segment will +match all remaining bytes in the input; such a segment may only be +used at the end of a pattern, when matching. + +The size may also be given as an integer variable matched earlier in +the pattern, as in the example given at the top. When constructing, a +size may be a variable referring to the supplied environment. + +In builders, numbers will be rounded, masked or padded to fit the size +and units given; for example, `'256:8'` gives the binary `Buffer<00>` +because the lowest eight bits are 0; `'255:16` gives the binary +`Buffer<00 ff>`. + +### Type name specifier + +One of `integer`, `binary`, `string`, `float`. If not given, the +default is `integer`. + +An integer is a big- or little-endian, signed or unsigned +integer. Integers up to 32 bits are supported. Signed integers are +two's complement format. In JavaScript, only integers between -(2^53) +and 2^53 can be represented, and bitwise operators are only defined on +32-bit signed integers. + +A binary is simply a byte buffer; usually this will result in a slice +of the input buffer being returned, so beware mutation. + +A string is a UTF8 string consisting of the given number of bytes. + +A float is a 32- or 64-bit IEEE754 floating-point value (this is the +standard JavaScript uses, as do Java and Erlang). + +### Endianness specifier + +Integers may be big- or little-endian; this refers to which 'end' of +the bytes making up the integer are most significant. In network +protocols integers are usually big-endian, meaning the first +(left-most) byte is the most significant, but this is not always the +case. + +A specifier of `big` means the integer will be parsed (or written into +the result) as big-endian, and `little` means the integer will be +parsed or written as little-endian. The default is big-endian. + +### Signedness specifier + +Integer segments may include a specifier of `signed` or `unsigned`. A +signed integer is parsed as two's complement format. The default is +unsigned. + +Signedness is ignored in builders. + +### Literal strings + +A quoted string appearing in a pattern is a shorthand for the bytes in +its UTF8 encoding. For example, + + "foobar", _/binary + +matches any buffer that starts with the bytes `0x66, 0x6f, 0x6f, 0x62, +0x61, 0x72`. + +When used in a builder, a quoted string is copied into the result as +the bytes of its UTF8 encoding. + +## Examples + +In the following the matched bytes are given in array notation for +convenience. Bear in mind that `match()` actually takes a buffer for +the bytes to match against. The phrase "returns X as Y" or "binds X as +Y" means the return value is an object with value X mapped to the key +Y. + + 54 + +Matches the single byte `54`. + + 54:32 + +Matches the bytes [0,0,0,54]. + + 54:32/little + +Matches the bytes [54,0,0,0]. + + 54:4/unit:8 + +Matches the bytes [0,0,0,54]. + + int:32/signed + +Matches a binary of four bytes, and returns a signed 32-bit integer as +`int`. + + len:16, str:len/binary + +Matches a binary of `2 + len` bytes, and returns an unsigned 16-bit +integer as `len` and a buffer of length `len` as `str`. + + len:16, _:len/binary, rest/binary + +Matches a binary of at least `2 + len` bytes, binds an unsigned 16-bit +integer as `len`, ignores the next `len` bytes, and binds the +remaining (possibly zero-length) binary as `rest`. + + s:8, key:s/binary, value/binary + +When given the environment `{s:6, key: "foobar"}`, will match a binary +starting with [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, ...]. diff --git a/node_modules/bitsyntax/index.js b/node_modules/bitsyntax/index.js new file mode 100644 index 0000000..3a894a9 --- /dev/null +++ b/node_modules/bitsyntax/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports.parse = require('./lib/parse').parse; +module.exports.match = require('./lib/interp').match; +module.exports.build = require('./lib/constructor').build; +module.exports.write = require('./lib/constructor').write; + +module.exports.matcher = module.exports.compile = + require('./lib/compile').compile; +module.exports.builder = require('./lib/compile').compile_builder; diff --git a/node_modules/bitsyntax/lib/compile.js b/node_modules/bitsyntax/lib/compile.js new file mode 100644 index 0000000..969ccd3 --- /dev/null +++ b/node_modules/bitsyntax/lib/compile.js @@ -0,0 +1,303 @@ +// Compile patterns to recognisers and constructors + +'use strict'; + +require('buffer-more-ints'); +var $ = require('util').format; + +var parse = require('./parse').parse; +var interp = require('./interp'), + parse_int = interp.parse_int, + parse_float = interp.parse_float; +var construct = require('./constructor'), + write_int = construct.write_int, + write_float = construct.write_float; + +var Buffer = require('safe-buffer').Buffer; + +var lines = []; +function $start() { + lines = []; +} +function $line(/* format , args */) { + lines.push($.apply(null, arguments)); +} +function $result() { + return lines.join('\n'); +} + +function bits_expr(segment) { + if (typeof segment.size === 'string') { + return $('%s * %d', var_name(segment.size), segment.unit); + } + else { + return (segment.size * segment.unit).toString(); + } +} + +function get_number(segment) { + $line('bits = %s;\n', bits_expr(segment)); + var parser = (segment.type === 'integer') ? + 'parse_int' : 'parse_float'; + var be = segment.bigendian, sg = segment.signed; + $line("byteoffset = offset / 8; offset += bits"); + $line("if (offset > binsize) { return false; }"); + $line("else { result = %s(bin, byteoffset, bits / 8, %s, %s); }", + parser, be, sg); +} + +function get_binary(segment) { + $line("byteoffset = offset / 8;"); + if (segment.size === true) { + $line("offset = binsize;"); + $line("result = bin.slice(byteoffset);"); + } + else { + $line("bits = %s;", bits_expr(segment)); + $line("offset += bits;"); + $line("if (offset > binsize) { return false; }"); + $line("else { result = bin.slice(byteoffset,", + "byteoffset + bits / 8); }"); + } +} + +function get_string(segment) { + $line("byteoffset = offset / 8;"); + var strlen = segment.value.length; + var strlenbits = strlen * 8; + $line("offset += %d;", strlenbits); + $line("if (offset > binsize) { return false; }"); + $line("else { result = bin.toString(byteoffset,", + $("byteoffset + %d); }", strlen)); +} + +function skip_bits(segment) { + if (typeof segment.size === 'string') { + // Damn. Have to look up the size. + $line("var skipbits = %s * %d;", + var_name(segment.size), segment.unit); + $line("if (offset + skipbits > binsize) { return false; }"); + $line("else { offset += skipbits; }"); + } + else if (segment.size === true) { + $line("if (offset % 8 === 0) { offset = binsize; }"); + $line("else { return false; }"); + } + else { + var bits = segment.unit * segment.size; + $line("if (offset + %d > binsize) { return false; }", bits); + $line("else { offset += %d; }", bits); + } +} + +function match_seg(segment) { + if (segment.name === '_') { + skip_bits(segment); + } + else { + var assign_result; + switch (segment.type) { + case 'integer': + case 'float': + get_number(segment); + break; + case 'binary': + get_binary(segment); + break; + case 'string': + get_string(segment); + break; + } + $line("if (result === false) return false;"); + if (segment.name) { + // variable is given a value in the environment + $line("else if (%s !== undefined) {", var_name(segment.name)); + // .. and it is not the same as that matched + $line("if (%s != result) return false;", + var_name(segment.name)); + $line("}"); + // variable is free + $line('else %s = result;', var_name(segment.name)); + } + else { + var repr = JSON.stringify(segment.value); + $line("else if (result != %s) return false;", repr); + } + } +} + +function var_name(name) { + return 'var_' + name; +} + +function variables(segments) { + var names = {}; + for (var i = 0; i < segments.length; i++) { + var name = segments[i].name; + if (name && name !== '_') { + names[name] = true; + } + name = segments[i].size; + if (typeof name === 'string') { + names[name] = true; + } + } + return Object.keys(names); +} + +function compile_pattern(segments) { + $start(); + $line("return function(binary, env) {"); + $line("'use strict';"); + $line("var bin = binary, env = env || {};"); + $line("var offset = 0, binsize = bin.length * 8;"); + $line("var bits, result, byteoffset;"); + var varnames = variables(segments); + for (var v = 0; v < varnames.length; v++) { + var name = varnames[v]; + $line("var %s = env['%s'];", var_name(name), name); + } + + var len = segments.length; + for (var i = 0; i < len; i++) { + var segment = segments[i]; + $line("// " + JSON.stringify(segment)); + match_seg(segment); + } + + $line("if (offset == binsize) {"); + $line("return {"); + for (var v = 0; v < varnames.length; v++) { + var name = varnames[v]; + $line("%s: %s,", name, var_name(name)); + } + $line('};'); + $line('}'); // if offset == binsize + $line("else return false;"); + $line("}"); // end function + + var fn = new Function('parse_int', 'parse_float', $result()); + return fn(parse_int, parse_float); +} + + +function write_seg(segment) { + switch (segment.type) { + case 'string': + $line("offset += buf.write(%s, offset, 'utf8');", + JSON.stringify(segment.value)); + break; + case 'binary': + $line("val = bindings['%s'];", segment.name); + if (segment.size === true) { + $line('size = val.length;'); + } + else if (typeof segment.size === 'string') { + $line("size = (bindings['%s'] * %d) / 8;", + segment.size, segment.unit); + } + else { + $line("size = %d;", (segment.size * segment.unit) / 8); + } + $line('val.copy(buf, offset, 0, size);'); + $line('offset += size;'); + break; + case 'integer': + case 'float': + write_number(segment); + break; + } +} + +function write_number(segment) { + if (segment.name) { + $line("val = bindings['%s'];", segment.name); + } + else { + $line("val = %d", segment.value); + } + var writer = (segment.type === 'integer') ? + 'write_int' : 'write_float'; + if (typeof segment.size === 'string') { + $line("size = (bindings['%s'] * %d) / 8;", + segment.size, segment.unit); + } + else { + $line('size = %d;', (segment.size * segment.unit) / 8); + } + $line('%s(buf, val, offset, size, %s);', + writer, segment.bigendian); + $line('offset += size;'); +} + +function size_of(segments) { + var variable = []; + var fixed = 0; + + for (var i = 0; i < segments.length; i++) { + var segment = segments[i]; + if (typeof segment.size === 'string' || + segment.size === true) { + variable.push(segment); + } + else if (segment.type === 'string') { + fixed += Buffer.byteLength(segment.value); + } + else { + fixed += (segment.size * segment.unit) / 8; + } + } + + $line('var buffersize = %d;', fixed); + + if (variable.length > 0) { + for (var j = 0; j < variable.length; j++) { + var segment = variable[j]; + if (segment.size === true) { + $line("buffersize += bindings['%s'].length;", segment.name); + } + else { + $line("buffersize += (bindings['%s'] * %d) / 8;", + segment.size, segment.unit); + } + } + } +} + +function emit_write(segments) { + $line('var val, size;'); + + var len = segments.length; + for (var i = 0; i < len; i++) { + var segment = segments[i]; + $line('// %s', JSON.stringify(segment)); + write_seg(segment); + } +} + +function compile_ctor(segments) { + $start(); + $line('return function(bindings) {'); + $line("'use strict';"); + size_of(segments); + $line('var buf = Buffer.alloc(buffersize);'); + $line('var offset = 0;'); + emit_write(segments); + $line('return buf;'); + $line('}'); // end function + + return new Function('write_int', 'write_float', 'Buffer', + $result())(write_int, write_float, Buffer); +} + +module.exports.compile_pattern = compile_pattern; +module.exports.compile = function() { + var str = [].join.call(arguments, ','); + var p = parse(str); + return compile_pattern(p); +}; +module.exports.compile_builder = function() { + var str = [].join.call(arguments, ','); + var p = parse(str); + return compile_ctor(p); +}; diff --git a/node_modules/bitsyntax/lib/constructor.js b/node_modules/bitsyntax/lib/constructor.js new file mode 100644 index 0000000..c3b6422 --- /dev/null +++ b/node_modules/bitsyntax/lib/constructor.js @@ -0,0 +1,142 @@ +// -*- js-indent-level: 2 -*- + +// Constructors given patterns + +'use strict'; + +var ints = require('buffer-more-ints'); +var Buffer = require('safe-buffer').Buffer; + +// Interpret the pattern, writing values into a buffer +function write(buf, offset, pattern, bindings) { + for (var i=0, len = pattern.length; i < len; i++) { + var segment = pattern[i]; + switch (segment.type) { + case 'string': + offset += buf.write(segment.value, offset, 'utf8'); + break; + case 'binary': + offset += writeBinary(segment, buf, offset, bindings); + break; + case 'integer': + offset += writeInteger(segment, buf, offset, bindings); + break; + case 'float': + offset += writeFloat(segment, buf, offset, bindings); + break; + } + } + return offset; +} + +function build(pattern, bindings) { + var bufsize = size_of(pattern, bindings); + var buf = Buffer.alloc(bufsize); + write(buf, 0, pattern, bindings); + return buf; +} + +// In bytes +function size_of_segment(segment, bindings) { + // size refers to a variable + if (typeof segment.size === 'string') { + return (bindings[segment.size] * segment.unit) / 8; + } + if (segment.type === 'string') { + return Buffer.byteLength(segment.value, 'utf8'); + } + if (segment.type === 'binary' && segment.size === true) { + var val = bindings[segment.name]; + return val.length; + } + return (segment.size * segment.unit) / 8; +} + +// size of the to-be-constructed binary, in bytes +function size_of(segments, bindings) { + var size = 0; + for (var i=0, len = segments.length; i < len; i++) { + size += size_of_segment(segments[i], bindings); + } + return size; +} + +function writeBinary(segment, buf, offset, bindings) { + var bin = bindings[segment.name]; + var size = size_of_segment(segment, bindings); + bin.copy(buf, offset, 0, size); + return size; +} + +// TODO in ff might use the noAssert argument to Buffer.write*() but +// need to check that it does the right thing wrt little-endian + +function writeInteger(segment, buf, offset, bindings) { + var value = (segment.name) ? bindings[segment.name] : segment.value; + var size = size_of_segment(segment, bindings); + return write_int(buf, value, offset, size, segment.bigendian); +} + +function write_int(buf, value, offset, size, bigendian) { + switch (size) { + case 1: + buf.writeUInt8(value, offset); + break; + case 2: + (bigendian) ? + buf.writeUInt16BE(value, offset) : + buf.writeUInt16LE(value, offset); + break; + case 4: + (bigendian) ? + buf.writeUInt32BE(value, offset) : + buf.writeUInt32LE(value, offset); + break; + case 8: + (bigendian) ? + ints.writeUInt64BE(buf, value, offset) : + ints.writeUInt64LE(buf, value, offset); + break; + default: + throw new Error("integer size * unit must be 8, 16, 32 or 64"); + } + return size; +} + +function writeFloat(segment, buf, offset, bindings) { + var value = (segment.name) ? bindings[segment.name] : segment.value; + var size = size_of_segment(segment, bindings); + return write_float(buf, value, offset, size, segment.bigendian); +} + +function write_float(buf, value, offset, size, bigendian) { + if (size === 4) { + (bigendian) ? + buf.writeFloatBE(value, offset) : + buf.writeFloatLE(value, offset); + } + else if (size === 8) { + (bigendian) ? + buf.writeDoubleBE(value, offset) : + buf.writeDoubleLE(value, offset); + } + else { + throw new Error("float size * unit must be 32 or 64"); + } + return size; +} + +var parse = require('./parse').parse; + +module.exports.write = write; +module.exports.build = build; +module.exports.write_int = write_int; +module.exports.write_float = write_float; + +module.exports.builder = function(pstr) { + pstr = (arguments.length > 1) ? [].join.call(arguments, ',') : pstr; + var pattern = parse(pstr); + return function(vars) { + return build(pattern, vars); + }; +}; diff --git a/node_modules/bitsyntax/lib/grammar.pegjs b/node_modules/bitsyntax/lib/grammar.pegjs new file mode 100644 index 0000000..e96023b --- /dev/null +++ b/node_modules/bitsyntax/lib/grammar.pegjs @@ -0,0 +1,67 @@ + +start + = ws head:segment tail:segmentTail* { tail.unshift(head); return tail; } + +segmentTail + = ws ',' ws seg:segment { return seg; } + +segment + = str:string { return {string: str}; } + / v:identifier size:size ? specs:specifierList ? + { return {name: v, size: size, specifiers: specs}; } + / v:number size:size ? specs:specifierList ? + { return {value: v, size: size, specifiers: specs}; } + +string + = '"' '"' { return ""; } + / '"' chars:chars '"' { return chars; } + +/* From JSON example +https://github.com/dmajda/pegjs/blob/master/examples/json.pegjs */ + +chars + = chars:char+ { return chars.join(""); } + +char + = [^"\\\0-\x1F\x7f] + / '\\"' { return '"'; } + / "\\\\" { return "\\"; } + / "\\/" { return "/"; } + / "\\b" { return "\b"; } + / "\\f" { return "\f"; } + / "\\n" { return "\n"; } + / "\\r" { return "\r"; } + / "\\t" { return "\t"; } + / "\\u" h1:hexDigit h2:hexDigit h3:hexDigit h4:hexDigit { + return String.fromCharCode(parseInt("0x" + h1 + h2 + h3 + h4)); + } + +hexDigit + = [0-9a-fA-F] + +identifier + = (head:[_a-zA-Z] tail:[_a-zA-Z0-9]*) { return head + tail.join(''); } + +number + = '0' { return 0; } + / head:[1-9] tail:[0-9]* { return parseInt(head + tail.join('')); } + +size + = ':' num:number { return num; } + / ':' id:identifier { return id; } + +specifierList + = '/' head:specifier tail:specifierTail* { tail.unshift(head); return tail; } + +specifierTail + = '-' spec:specifier { return spec; } + +specifier + = 'little' / 'big' / 'signed' / 'unsigned' + / 'integer' / 'binary' / 'float' + / unit + +unit + = 'unit:' num:number { return 'unit:' + num; } + +ws = [ \t\n]* diff --git a/node_modules/bitsyntax/lib/interp.js b/node_modules/bitsyntax/lib/interp.js new file mode 100644 index 0000000..264bc82 --- /dev/null +++ b/node_modules/bitsyntax/lib/interp.js @@ -0,0 +1,232 @@ +// -*- js-indent: 2 -*- +// Interpreter for bit syntax AST. +// Grammar: +// +// pattern := segment ("," segment)* +// segment := (value | var) (":" size)? ("/" specifier ("-" specifier)*)? | string +// var := "_" | identifier +// size := integer | var +// specifier := "little" | "big" | "signed" | "unsigned" | "unit" ":" 0..256 | type +// type := "integer" | "binary" | "float" +// +// where integer has the obvious meaning, and identifier is anything +// other than "_" that fits the JavaScript identifier specification. +// + +// We'll use an object to represent each segment, and an array of +// segments for a pattern. We won't try to optimise for groups of +// patterns; we'll just step through each to see if it works. We rely +// a hypothetical prior step to check that it's a valid pattern. + +// ? compile to intermediate instructions ? + +// A segment looks like +// { +// type: string, // 'string' is special case +// size: integer | true, // true means 'all remaining' +// name: string | null, // (may be '_') +// value: value | null, // either name OR value +// unit: integer, +// signed: boolean, +// bigendian: boolean +// } + +'use strict'; + +var ints = require('buffer-more-ints'), + debug = require('debug')('bitsyntax-Interpreter'); + +function parse_int(bin, off, sizeInBytes, bigendian, signed) { + switch (sizeInBytes) { + case 1: + return (signed) ? bin.readInt8(off) : bin.readUInt8(off); + case 2: + return (bigendian) ? + (signed) ? bin.readInt16BE(off) : bin.readUInt16BE(off) : + (signed) ? bin.readInt16LE(off) : bin.readUInt16LE(off); + case 4: + return (bigendian) ? + (signed) ? bin.readInt32BE(off) : bin.readUInt32BE(off) : + (signed) ? bin.readInt32LE(off) : bin.readUInt32LE(off); + case 8: + return (bigendian) ? + ((signed) ? ints.readInt64BE : ints.readUInt64BE)(bin, off) : + ((signed) ? ints.readInt64LE : ints.readUInt64LE)(bin, off); + default: + throw "Integers must be 8-, 16-, 32- or 64-bit"; + } +} + +function parse_float(bin, off, sizeInBytes, bigendian) { + switch (sizeInBytes) { + case 4: + return (bigendian) ? bin.readFloatBE(off) : bin.readFloatLE(off); + case 8: + return (bigendian) ? bin.readDoubleBE(off) : bin.readDoubleLE(off); + default: + throw "Floats must be 32- or 64-bit"; + } +} + +function size_of(segment, bound) { + var size = segment.size; + if (typeof size === 'string') { + return bound[size]; + } + else { + return size; + } +} + +function new_scope(env) { + function scope() {}; + scope.prototype = env; + return new scope(); +} + +function bindings(scope) { + var s = {}; + for (var k in scope) { + if (scope.hasOwnProperty(k)) { + s[k] = scope[k]; + } + } + return s; +} + +function match(pattern, binary, boundvars) { + var offset = 0, vars = new_scope(boundvars); + var binsize = binary.length * 8; + + function skip_bits(segment) { + debug("skip bits"); debug(segment); + var size = size_of(segment, vars); + if (size === true) { + if (offset % 8 === 0) { + offset = binsize; + return true; + } + else { + return false; + } + } + + var bits = segment.unit * size; + if (offset + bits > binsize) { + return false; + } + else { + offset += bits; + } + } + + function get_integer(segment) { + debug("get_integer"); debug(segment); + // let's do only multiples of eight bits for now + var unit = segment.unit, size = size_of(segment, vars); + var bitsize = size * unit; + var byteoffset = offset / 8; // NB assumes aligned + offset += bitsize; + if (bitsize % 8 > 0 || (offset > binsize)) { + return false; + } + else { + return parse_int(binary, byteoffset, bitsize / 8, + segment.bigendian, segment.signed); + } + } + + function get_float(segment) { + debug("get_float"); debug(segment); + var unit = segment.unit; var size = size_of(segment, vars); + var bitsize = size * unit; + var byteoffset = offset / 8; // assume aligned + offset += bitsize; + if (offset > binsize) { + return false; + } + else { + return parse_float(binary, byteoffset, + bitsize / 8, segment.bigendian); + } + } + + function get_binary(segment) { + debug("get_binary"); debug(segment); + var unit = segment.unit, size = size_of(segment, vars); + var byteoffset = offset / 8; // NB alignment + + if (size === true) { + offset = binsize; + return binary.slice(byteoffset); + } + else { + var bitsize = size * unit; + if (bitsize % 8 > 0 || (offset + bitsize) > binsize) { + return false; + } + else { + offset += bitsize; + return binary.slice(byteoffset, byteoffset + bitsize / 8); + } + } + } + + function get_string(segment) { + debug("get_string"); debug(segment); + var len = segment.value.length; + var byteoffset = offset / 8; + + offset += len * 8; + if (offset > binsize) { + return false; + } + // FIXME bytes vs UTF8 characters + return binary.slice(byteoffset, byteoffset + len).toString('utf8'); + } + + var patternlen = pattern.length; + for (var i = 0; i < patternlen; i++) { + var segment = pattern[i]; + var result = false; + if (segment.name === '_') { + result = skip_bits(segment); + } + else { + switch (segment.type) { + case 'string': + result = get_string(segment); + break; + case 'integer': + result = get_integer(segment); + break; + case 'float': + result = get_float(segment); + break; + case 'binary': + result = get_binary(segment); + break; + } + + if (result === false) { + return false; + } + else if (segment.name) { + vars[segment.name] = result; + } + else if (segment.value != result) { + return false; + } + } + } + if (offset == binsize) { + return bindings(vars); + } + else { + return false; + } +} + +module.exports.match = match; +module.exports.parse_int = parse_int; +module.exports.parse_float = parse_float; diff --git a/node_modules/bitsyntax/lib/parse.js b/node_modules/bitsyntax/lib/parse.js new file mode 100644 index 0000000..40a10d6 --- /dev/null +++ b/node_modules/bitsyntax/lib/parse.js @@ -0,0 +1,32 @@ +// Parse patterns in string form into the form we use for interpreting +// (and later, for compiling). + +'use strict'; + +var ast = require('./pattern'); +var parser = require('./parser'); + +function parse_pattern(string) { + var segments = parser.parse(string); + for (var i=0, len = segments.length; i < len; i++) { + var s = segments[i]; + if (s.string != undefined) { + segments[i] = ast.string(s.string); + } + else if (s.value != undefined) { + segments[i] = ast.value(s.value, s.size, s.specifiers); + } + else if (s.name != undefined) { + segments[i] = ast.variable(s.name, s.size, s.specifiers); + } + else { + throw "Unknown segment " + s; + } + } + return segments; +} + +module.exports.parse = function() { + var str = [].join.call(arguments, ','); + return parse_pattern(str); +}; diff --git a/node_modules/bitsyntax/lib/parser.js b/node_modules/bitsyntax/lib/parser.js new file mode 100644 index 0000000..3658ff8 --- /dev/null +++ b/node_modules/bitsyntax/lib/parser.js @@ -0,0 +1,1173 @@ +module.exports = (function(){ + /* + * Generated by PEG.js 0.7.0. + * + * http://pegjs.majda.cz/ + */ + + function quote(s) { + /* + * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a + * string literal except for the closing quote character, backslash, + * carriage return, line separator, paragraph separator, and line feed. + * Any character may appear in the form of an escape sequence. + * + * For portability, we also escape escape all control and non-ASCII + * characters. Note that "\0" and "\v" escape sequences are not used + * because JSHint does not like the first and IE the second. + */ + return '"' + s + .replace(/\\/g, '\\\\') // backslash + .replace(/"/g, '\\"') // closing quote character + .replace(/\x08/g, '\\b') // backspace + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + + '"'; + } + + var result = { + /* + * Parses the input with a generated parser. If the parsing is successfull, + * returns a value explicitly or implicitly specified by the grammar from + * which the parser was generated (see |PEG.buildParser|). If the parsing is + * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. + */ + parse: function(input, startRule) { + var parseFunctions = { + "start": parse_start, + "segmentTail": parse_segmentTail, + "segment": parse_segment, + "string": parse_string, + "chars": parse_chars, + "char": parse_char, + "hexDigit": parse_hexDigit, + "identifier": parse_identifier, + "number": parse_number, + "size": parse_size, + "specifierList": parse_specifierList, + "specifierTail": parse_specifierTail, + "specifier": parse_specifier, + "unit": parse_unit, + "ws": parse_ws + }; + + if (startRule !== undefined) { + if (parseFunctions[startRule] === undefined) { + throw new Error("Invalid rule name: " + quote(startRule) + "."); + } + } else { + startRule = "start"; + } + + var pos = 0; + var reportFailures = 0; + var rightmostFailuresPos = 0; + var rightmostFailuresExpected = []; + + function padLeft(input, padding, length) { + var result = input; + + var padLength = length - input.length; + for (var i = 0; i < padLength; i++) { + result = padding + result; + } + + return result; + } + + function escape(ch) { + var charCode = ch.charCodeAt(0); + var escapeChar; + var length; + + if (charCode <= 0xFF) { + escapeChar = 'x'; + length = 2; + } else { + escapeChar = 'u'; + length = 4; + } + + return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); + } + + function matchFailed(failure) { + if (pos < rightmostFailuresPos) { + return; + } + + if (pos > rightmostFailuresPos) { + rightmostFailuresPos = pos; + rightmostFailuresExpected = []; + } + + rightmostFailuresExpected.push(failure); + } + + function parse_start() { + var result0, result1, result2, result3; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_ws(); + if (result0 !== null) { + result1 = parse_segment(); + if (result1 !== null) { + result2 = []; + result3 = parse_segmentTail(); + while (result3 !== null) { + result2.push(result3); + result3 = parse_segmentTail(); + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { tail.unshift(head); return tail; })(pos0, result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_segmentTail() { + var result0, result1, result2, result3; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_ws(); + if (result0 !== null) { + if (input.charCodeAt(pos) === 44) { + result1 = ","; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\",\""); + } + } + if (result1 !== null) { + result2 = parse_ws(); + if (result2 !== null) { + result3 = parse_segment(); + if (result3 !== null) { + result0 = [result0, result1, result2, result3]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, seg) { return seg; })(pos0, result0[3]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_segment() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + result0 = parse_string(); + if (result0 !== null) { + result0 = (function(offset, str) { return {string: str}; })(pos0, result0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_identifier(); + if (result0 !== null) { + result1 = parse_size(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = parse_specifierList(); + result2 = result2 !== null ? result2 : ""; + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, v, size, specs) { return {name: v, size: size, specifiers: specs}; })(pos0, result0[0], result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_number(); + if (result0 !== null) { + result1 = parse_size(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = parse_specifierList(); + result2 = result2 !== null ? result2 : ""; + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, v, size, specs) { return {value: v, size: size, specifiers: specs}; })(pos0, result0[0], result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + } + } + return result0; + } + + function parse_string() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 34) { + result0 = "\""; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result0 !== null) { + if (input.charCodeAt(pos) === 34) { + result1 = "\""; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return ""; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 34) { + result0 = "\""; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result0 !== null) { + result1 = parse_chars(); + if (result1 !== null) { + if (input.charCodeAt(pos) === 34) { + result2 = "\""; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, chars) { return chars; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + } + return result0; + } + + function parse_chars() { + var result0, result1; + var pos0; + + pos0 = pos; + result1 = parse_char(); + if (result1 !== null) { + result0 = []; + while (result1 !== null) { + result0.push(result1); + result1 = parse_char(); + } + } else { + result0 = null; + } + if (result0 !== null) { + result0 = (function(offset, chars) { return chars.join(""); })(pos0, result0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_char() { + var result0, result1, result2, result3, result4; + var pos0, pos1; + + if (/^[^"\\\0-\x1F]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[^\"\\\\\\0-\\x1F]"); + } + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\\"") { + result0 = "\\\""; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\\\"\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return '"'; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\\\") { + result0 = "\\\\"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\\\\\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\\"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\/") { + result0 = "\\/"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\/\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "/"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\b") { + result0 = "\\b"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\b\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\b"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\f") { + result0 = "\\f"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\f\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\f"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\n") { + result0 = "\\n"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\n\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\n"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\r") { + result0 = "\\r"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\r\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\r"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + if (input.substr(pos, 2) === "\\t") { + result0 = "\\t"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\t\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return "\t"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 2) === "\\u") { + result0 = "\\u"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\u\""); + } + } + if (result0 !== null) { + result1 = parse_hexDigit(); + if (result1 !== null) { + result2 = parse_hexDigit(); + if (result2 !== null) { + result3 = parse_hexDigit(); + if (result3 !== null) { + result4 = parse_hexDigit(); + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, h1, h2, h3, h4) { + return String.fromCharCode(parseInt("0x" + h1 + h2 + h3 + h4)); + })(pos0, result0[1], result0[2], result0[3], result0[4]); + } + if (result0 === null) { + pos = pos0; + } + } + } + } + } + } + } + } + } + } + return result0; + } + + function parse_hexDigit() { + var result0; + + if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[0-9a-fA-F]"); + } + } + return result0; + } + + function parse_identifier() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (/^[_a-zA-Z]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[_a-zA-Z]"); + } + } + if (result0 !== null) { + result1 = []; + if (/^[_a-zA-Z0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[_a-zA-Z0-9]"); + } + } + while (result2 !== null) { + result1.push(result2); + if (/^[_a-zA-Z0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[_a-zA-Z0-9]"); + } + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { return head + tail.join(''); })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_number() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + if (input.charCodeAt(pos) === 48) { + result0 = "0"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"0\""); + } + } + if (result0 !== null) { + result0 = (function(offset) { return 0; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (/^[1-9]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[1-9]"); + } + } + if (result0 !== null) { + result1 = []; + if (/^[0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + while (result2 !== null) { + result1.push(result2); + if (/^[0-9]/.test(input.charAt(pos))) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { return parseInt(head + tail.join('')); })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + } + return result0; + } + + function parse_size() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 58) { + result0 = ":"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":\""); + } + } + if (result0 !== null) { + result1 = parse_number(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, num) { return num; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 58) { + result0 = ":"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":\""); + } + } + if (result0 !== null) { + result1 = parse_identifier(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, id) { return id; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + } + return result0; + } + + function parse_specifierList() { + var result0, result1, result2, result3; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 47) { + result0 = "/"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"/\""); + } + } + if (result0 !== null) { + result1 = parse_specifier(); + if (result1 !== null) { + result2 = []; + result3 = parse_specifierTail(); + while (result3 !== null) { + result2.push(result3); + result3 = parse_specifierTail(); + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { tail.unshift(head); return tail; })(pos0, result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_specifierTail() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 45) { + result0 = "-"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"-\""); + } + } + if (result0 !== null) { + result1 = parse_specifier(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, spec) { return spec; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_specifier() { + var result0; + + if (input.substr(pos, 6) === "little") { + result0 = "little"; + pos += 6; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"little\""); + } + } + if (result0 === null) { + if (input.substr(pos, 3) === "big") { + result0 = "big"; + pos += 3; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"big\""); + } + } + if (result0 === null) { + if (input.substr(pos, 6) === "signed") { + result0 = "signed"; + pos += 6; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"signed\""); + } + } + if (result0 === null) { + if (input.substr(pos, 8) === "unsigned") { + result0 = "unsigned"; + pos += 8; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"unsigned\""); + } + } + if (result0 === null) { + if (input.substr(pos, 7) === "integer") { + result0 = "integer"; + pos += 7; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"integer\""); + } + } + if (result0 === null) { + if (input.substr(pos, 6) === "binary") { + result0 = "binary"; + pos += 6; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"binary\""); + } + } + if (result0 === null) { + if (input.substr(pos, 5) === "float") { + result0 = "float"; + pos += 5; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"float\""); + } + } + if (result0 === null) { + result0 = parse_unit(); + } + } + } + } + } + } + } + return result0; + } + + function parse_unit() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 5) === "unit:") { + result0 = "unit:"; + pos += 5; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"unit:\""); + } + } + if (result0 !== null) { + result1 = parse_number(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, num) { return 'unit:' + num; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_ws() { + var result0, result1; + + result0 = []; + if (/^[ \t\n]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("[ \\t\\n]"); + } + } + while (result1 !== null) { + result0.push(result1); + if (/^[ \t\n]/.test(input.charAt(pos))) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("[ \\t\\n]"); + } + } + } + return result0; + } + + + function cleanupExpected(expected) { + expected.sort(); + + var lastExpected = null; + var cleanExpected = []; + for (var i = 0; i < expected.length; i++) { + if (expected[i] !== lastExpected) { + cleanExpected.push(expected[i]); + lastExpected = expected[i]; + } + } + return cleanExpected; + } + + function computeErrorPosition() { + /* + * The first idea was to use |String.split| to break the input up to the + * error position along newlines and derive the line and column from + * there. However IE's |split| implementation is so broken that it was + * enough to prevent it. + */ + + var line = 1; + var column = 1; + var seenCR = false; + + for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { + var ch = input.charAt(i); + if (ch === "\n") { + if (!seenCR) { line++; } + column = 1; + seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + line++; + column = 1; + seenCR = true; + } else { + column++; + seenCR = false; + } + } + + return { line: line, column: column }; + } + + + var result = parseFunctions[startRule](); + + /* + * The parser is now in one of the following three states: + * + * 1. The parser successfully parsed the whole input. + * + * - |result !== null| + * - |pos === input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 2. The parser successfully parsed only a part of the input. + * + * - |result !== null| + * - |pos < input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 3. The parser did not successfully parse any part of the input. + * + * - |result === null| + * - |pos === 0| + * - |rightmostFailuresExpected| contains at least one failure + * + * All code following this comment (including called functions) must + * handle these states. + */ + if (result === null || pos !== input.length) { + var offset = Math.max(pos, rightmostFailuresPos); + var found = offset < input.length ? input.charAt(offset) : null; + var errorPosition = computeErrorPosition(); + + throw new this.SyntaxError( + cleanupExpected(rightmostFailuresExpected), + found, + offset, + errorPosition.line, + errorPosition.column + ); + } + + return result; + }, + + /* Returns the parser source code. */ + toSource: function() { return this._source; } + }; + + /* Thrown when a parser encounters a syntax error. */ + + result.SyntaxError = function(expected, found, offset, line, column) { + function buildMessage(expected, found) { + var expectedHumanized, foundHumanized; + + switch (expected.length) { + case 0: + expectedHumanized = "end of input"; + break; + case 1: + expectedHumanized = expected[0]; + break; + default: + expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + + " or " + + expected[expected.length - 1]; + } + + foundHumanized = found ? quote(found) : "end of input"; + + return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; + } + + this.name = "SyntaxError"; + this.expected = expected; + this.found = found; + this.message = buildMessage(expected, found); + this.offset = offset; + this.line = line; + this.column = column; + }; + + result.SyntaxError.prototype = Error.prototype; + + return result; +})(); diff --git a/node_modules/bitsyntax/lib/pattern.js b/node_modules/bitsyntax/lib/pattern.js new file mode 100644 index 0000000..8be9624 --- /dev/null +++ b/node_modules/bitsyntax/lib/pattern.js @@ -0,0 +1,116 @@ +// -*- js-indent-level: 2 -*- +// Constructing patterns + +'use strict'; + +function set(values) { + var s = {}; + for (var i in values) { + s[values[i]] = 1; + } + return s; +} + +// Construct a segment bound to a variable, e.g., from a segment like +// "Len:32/unsigned-big". `specifiers0` is an array. +function variable(name, size, specifiers0) { + var specifiers = set(specifiers0); + var segment = {name: name}; + segment.type = type_in(specifiers); + specs(segment, segment.type, specifiers); + segment.size = size_of(segment, segment.type, size, segment.unit); + return segment; +} + +module.exports.variable = variable; +module.exports.rest = function() { + return variable('_', true, ['binary']); +} + +// Construct a segment with a literal value, e.g., from a segment like +// "206". `specifiers0` is an array. + +function value(val, size, specifiers0) { + var specifiers = set(specifiers0); + var segment = {value: val}; + segment.type = type_in(specifiers); + // TODO check type v. value .. + specs(segment, segment.type, specifiers); + segment.size = size_of(segment, segment.type, size, segment.unit); + return segment; +} + +module.exports.value = value; + +// A string can appear as a literal, but it must appear without +// specifiers. +function string(val) { + return {value: val, type: 'string'}; +} +module.exports.string = string; + +var TYPES = {'integer': 1, 'binary': 1, 'float': 1}; +function type_in(specifiers) { + for (var t in specifiers) { + if (TYPES[t]) { return t; } + } + return 'integer'; +} + +function specs(segment, type, specifiers) { + switch (type) { + case 'integer': + segment.signed = signed_in(specifiers); + // fall through + case 'float': + segment.bigendian = endian_in(specifiers); + // fall through + default: + segment.unit = unit_in(specifiers, segment.type); + } + return segment; +} + +function endian_in(specifiers) { + // default is big, but I have chosen true = bigendian + return !specifiers['little']; +} + +function signed_in(specifiers) { + // this time I got it right; default is unsigned + return specifiers['signed']; +} + +function unit_in(specifiers, type) { + for (var s in specifiers) { + if (s.substr(0, 5) == 'unit:') { + var unit = parseInt(s.substr(5)); + // TODO check sane for type + return unit; + } + } + // OK defaults then + switch (type) { + case 'binary': + return 8; + case 'integer': + case 'float': + return 1; + } +} + +function size_of(segment, type, size, unit) { + if (size !== undefined && size !== '') { + return size; + } + else { + switch (type) { + case 'integer': + return 8; + case 'float': + return 64; + case 'binary': + return true; + } + } +} diff --git a/node_modules/bitsyntax/node_modules/safe-buffer/LICENSE b/node_modules/bitsyntax/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/bitsyntax/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +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 +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/bitsyntax/node_modules/safe-buffer/README.md b/node_modules/bitsyntax/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/bitsyntax/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/bitsyntax/node_modules/safe-buffer/index.d.ts b/node_modules/bitsyntax/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/bitsyntax/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/bitsyntax/node_modules/safe-buffer/index.js b/node_modules/bitsyntax/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..22438da --- /dev/null +++ b/node_modules/bitsyntax/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/bitsyntax/node_modules/safe-buffer/package.json b/node_modules/bitsyntax/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..c59fe3d --- /dev/null +++ b/node_modules/bitsyntax/node_modules/safe-buffer/package.json @@ -0,0 +1,62 @@ +{ + "_from": "safe-buffer@~5.1.2", + "_id": "safe-buffer@5.1.2", + "_inBundle": false, + "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "_location": "/bitsyntax/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@~5.1.2", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "~5.1.2", + "saveSpec": null, + "fetchSpec": "~5.1.2" + }, + "_requiredBy": [ + "/bitsyntax" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", + "_spec": "safe-buffer@~5.1.2", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\bitsyntax", + "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/bitsyntax/package.json b/node_modules/bitsyntax/package.json new file mode 100644 index 0000000..7093a2e --- /dev/null +++ b/node_modules/bitsyntax/package.json @@ -0,0 +1,60 @@ +{ + "_from": "bitsyntax@~0.1.0", + "_id": "bitsyntax@0.1.0", + "_inBundle": false, + "_integrity": "sha512-ikAdCnrloKmFOugAfxWws89/fPc+nw0OOG1IzIE72uSOg/A3cYptKCjSUhDTuj7fhsJtzkzlv7l3b8PzRHLN0Q==", + "_location": "/bitsyntax", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bitsyntax@~0.1.0", + "name": "bitsyntax", + "escapedName": "bitsyntax", + "rawSpec": "~0.1.0", + "saveSpec": null, + "fetchSpec": "~0.1.0" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.1.0.tgz", + "_shasum": "b0c59acef03505de5a2ed62a2f763c56ae1d6205", + "_spec": "bitsyntax@~0.1.0", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "author": { + "name": "Michael Bridgen", + "email": "=0.8" + }, + "homepage": "https://github.com/squaremo/bitsyntax-js#readme", + "license": "MIT", + "main": "./index", + "name": "bitsyntax", + "repository": { + "type": "git", + "url": "git://github.com/squaremo/bitsyntax-js.git" + }, + "scripts": { + "prepublish": "make all", + "test": "make test" + }, + "version": "0.1.0" +} diff --git a/node_modules/bitsyntax/test/consing.js b/node_modules/bitsyntax/test/consing.js new file mode 100644 index 0000000..9f1347e --- /dev/null +++ b/node_modules/bitsyntax/test/consing.js @@ -0,0 +1,47 @@ +var assert = require('assert'); +var parse = require('../').parse; +var build = require('../').build; +var builder = require('../').builder; +var write = require('../').write; + +var Buffer = require('safe-buffer').Buffer; + +TEST_CASES = [ + ['n:8', {n:255}, [255]], + ['n:16', {n: 0xf0f0}, [240, 240]], + ['n:32', {n: 0x12345678}, [18,52,86,120]], + ['n:64', {n: 0xffffffffffffffff}, [255,255,255,255,255,255,255,255]], + + ['n:8, s/binary', {n: 255, s: Buffer.from("foobar")}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], + ['n:8, "foobar", m:8', {n: 255, m:0}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0]], + ['n:8, s:n/binary', {n:6, s: Buffer.from('foobar')}, [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], + ['n:8, s:n/binary', {n:4, s: Buffer.from('foobar')}, [4, 0x66, 0x6f, 0x6f, 0x62]], + ['n:size', {n:4, size:8}, [4]], + ['206:n/unit:8', {n:1}, [206]] +]; + +function bufferToArray(buf) { + return Array.prototype.slice.call(buf); +} + +suite("Construction", function() { + TEST_CASES.forEach(function(c) { + var p = parse(c[0]); + test(c[0], function() { + assert.deepEqual(c[2], bufferToArray(build(p, c[1]))); + }); + test(c[0], function() { + var buf = Buffer.alloc(1024); + var end = write(buf, 7, p, c[1]); + buf = buf.slice(7, end); + assert.deepEqual(c[2], bufferToArray(buf)); + }); + test(c[0], function() { + var cons = builder(c[0]); + var buf = cons(c[1]); + assert.deepEqual(c[2], bufferToArray(buf)); + }); + + }); + +}); diff --git a/node_modules/bitsyntax/test/matching.js b/node_modules/bitsyntax/test/matching.js new file mode 100644 index 0000000..082b16f --- /dev/null +++ b/node_modules/bitsyntax/test/matching.js @@ -0,0 +1,188 @@ +var match = require('../').match; +var parse = require('../').parse; +var compile = require('../').matcher; +var assert = require('assert'); + +var Buffer = require('safe-buffer').Buffer; + +var INT_TESTS = [ + ['n:8', + [[[255], 255]]], + ['n:8/signed', + [[[255], -1]]], + ['n:1/unit:8', + [[[129], 129]]], + ['n:1/unit:8-signed', + [[[129], -127]]], + + ['n:16', + [[[1, 255], 511]]], + ['n:16/signed', + [[[255, 65], -191]]], + ['n:16/little', + [[[255, 1], 511]]], + ['n:16/signed-little', + [[[65, 255], -191]]], + + ['n:32', + [[[45, 23, 97, 102], 756506982]]], + ['n:32/signed', + [[[245, 23, 97, 102], -183017114]]], + ['n:32/little', + [[[245, 23, 97, 102], 1717639157]]], + ['n:32/signed-little', + [[[245, 23, 97, 129], -2124343307]]], + + ['n:4/signed-little-unit:8', + [[[245, 23, 97, 129], -2124343307]]], + + ['n:64', + [[[1,2,3,4,5,6,7,8], 72623859790382856]]], + ['n:64/signed', + [[[255,2,3,4,5,6,7,8], -71491328285473016]]], + ['n:64/little', + [[[1,2,3,4,5,6,7,8], 578437695752307201]]], + ['n:64/little-signed', + [[[1,2,3,4,5,6,7,255], -70080650589044223]]], + ['n:8/signed-unit:8-little', + [[[1,2,3,4,5,6,7,255], -70080650589044223]]], +]; + +suite("Integer", + function() { + + INT_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + assert.deepEqual({n: tc[1]}, match(pattern, Buffer.from(tc[0]))); + }); + test(p[0], function() { + assert.deepEqual({n: tc[1]}, cpattern(Buffer.from(tc[0]))); + }); + }); + }); + }); + + +// test cases largely constructed in Erlang using e.g., +// Pi = math:pi(), <>. +FLOAT_TESTS = [ + ['n:32/float', + [[[64,73,15,219], Math.PI], + [[0, 0, 0, 0], 0.0 ]]], + + ['n:64/float', + [[[64,9,33,251,84,68,45,24], Math.PI], + [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], + + ['n:32/float-little', + [[[219, 15, 73, 64], Math.PI], + [[0, 0, 0, 0], 0.0]]], + + ['n:64/float-little', + [[[24, 45, 68, 84, 251, 33, 9, 64], Math.PI], + [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], + + ['n:4/float-unit:8', + [[[64,73,15,219], Math.PI], + [[0, 0, 0, 0], 0.0]]] +]; + +suite("Float", + function() { + var precision = 0.00001; + FLOAT_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + var m = match(pattern, Buffer.from(tc[0])); + assert.ok(m.n !== undefined); + assert.ok(Math.abs(tc[1] - m.n) < precision); + }); + test(p[0], function() { + var m = cpattern(Buffer.from(tc[0])); + assert.ok(m.n !== undefined); + assert.ok(Math.abs(tc[1] - m.n) < precision); + }); + }); + }); + }); + +BINARY_TESTS = [ + ['n:0/unit:8-binary', []], + ['n:1/unit:8-binary', [93]], + ['n:5/unit:8-binary', [1, 2, 3, 4, 5]], + ['n:32/unit:1-binary', [255, 254, 253, 252]] +]; + +suite("Binary", + function() { + BINARY_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + var prest = p[0] + ', _/binary'; + var patternrest = parse(prest); + var cpatternrest = compile(prest); + test(p[0], function() { + assert.deepEqual({n: Buffer.from(p[1])}, + match(pattern, Buffer.from(p[1]))); + assert.deepEqual({n: Buffer.from(p[1])}, + cpattern(Buffer.from(p[1]))); + }); + test(prest, function() { + var plusgarbage = p[1].concat([5, 98, 23, 244]); + assert.deepEqual({n: Buffer.from(p[1])}, + match(patternrest, Buffer.from(plusgarbage))); + assert.deepEqual({n: Buffer.from(p[1])}, + cpatternrest(Buffer.from(plusgarbage))); + }); + }); + }); + +var VAR_TESTS = [ + ['size, n:size', + [[[8, 5], 5], + [[32, 0, 0, 0, 167], 167]]], + + ['size, n:size/binary', + [[[2, 5, 6], Buffer.from([5, 6])]]], + + ['a, b:a, n:b', + [[[8, 32, 0, 0, 2, 100], 612]]] +]; + +suite("Environment", + function() { + VAR_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + assert.deepEqual(tc[1], match(pattern, Buffer.from(tc[0])).n); + }); + test(p[0], function() { + assert.deepEqual(tc[1], cpattern(Buffer.from(tc[0])).n); + }); + }); + }); + }); + +STRING_TESTS = [ + ['"foobar", n:8', "foobarA", 'A'.charCodeAt(0)], + ['n:8, "foobar", _/binary', "CfoobarGARBAGE", 'C'.charCodeAt(0)], + ['"foo, :-bar\\"", n:8, "another"', 'foo, :-bar"Zanother', 'Z'.charCodeAt(0)] +]; + +suite("String", + function() { + STRING_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + test(p[0], function() { + var res = match(pattern, Buffer.from(p[1])); + assert.equal(res.n, p[2]); + }); + }); + }); diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..b24e635 --- /dev/null +++ b/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2018 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. diff --git a/node_modules/bluebird/README.md b/node_modules/bluebird/README.md new file mode 100644 index 0000000..7c1dd66 --- /dev/null +++ b/node_modules/bluebird/README.md @@ -0,0 +1,57 @@ + + Promises/A+ logo + + + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](https://img.shields.io/badge/coverage-98%25-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 + +Bluebird is a fully featured promise library with focus on innovative features and performance + +See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. + +For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). + +### Note + +Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself. + +# Questions and issues + +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`. + + + +## Thanks + +Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. + +# License + +The MIT License (MIT) + +Copyright (c) 2013-2019 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. + diff --git a/node_modules/bluebird/changelog.md b/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..73b2eb6 --- /dev/null +++ b/node_modules/bluebird/changelog.md @@ -0,0 +1 @@ +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/node_modules/bluebird/js/browser/bluebird.core.js b/node_modules/bluebird/js/browser/bluebird.core.js new file mode 100644 index 0000000..24a8bf2 --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.core.js @@ -0,0 +1,3914 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 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 3.7.2 + * Features enabled: core + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!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) { + _drainQueueStep(queue); + } +} + +function _drainQueueStep(queue) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + } else { + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +} + +Async.prototype._drainQueues = function () { + _drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + _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 = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":17,"./schedule":18}],2:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +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._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + 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, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; + +},{}],3:[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")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise":15}],4:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":21}],5:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; + +},{}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var es5 = _dereq_("./es5"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); + } + + function unhandledRejectionClear() { + promises.length = 0; + } + + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; + + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + deferUnhandledRejectionCheck(this); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; + Context.deactivateLongStackTraces(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; + Context.activateLongStackTraces(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + + +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; + +var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); + } + } else { + return !util.global.dispatchEvent(e); + } + }; + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var eventData = { + detail: event, + cancelable: true + }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); + es5.defineProperty( + domEvent, "reason", {value: event.reason}); + + return dispatch(legacyHandlers[name], domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = new Event(name, { + cancelable: true + }); + domEvent.detail = event; + es5.defineProperty(domEvent, "promise", {value: event.promise}); + es5.defineProperty(domEvent, "reason", {value: event.reason}); + return dispatch(legacyHandlers[name], domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name, false, true, + event); + return dispatch(legacyHandlers[name], domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } + return Promise; +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._dereferenceTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (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 = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function longStackTracesDereferenceTrace() { + this._trace = undefined; +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", 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 = " (No stack trace)" === line || + stackFramePattern.test(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 && error.name != "SyntaxError") { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(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: error.name == "SyntaxError" ? stack : cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(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); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + 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 longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +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) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) 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; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +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.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = 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); +}; + +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 += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + 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 += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + 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; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false, + asyncHooks: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + asyncHooks: function() { + return config.asyncHooks; + }, + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; + +},{"./errors":9,"./es5":10,"./util":21}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; + +},{}],9:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util"); +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 + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5":10,"./util":21}],10:[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; + } + }; +} + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret === NEXT_FILTER) { + return ret; + } else if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; + +},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { +var util = _dereq_("./util"); +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 promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + 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 <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var context = Promise._getContext(); + holder.fn = util.contextBind(context, holder.fn); + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var args = [].slice.call(arguments);; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util":21}],13:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util":21}],14:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors"); +var OperationalError = errors.OperationalError; +var es5 = _dereq_("./es5"); + +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, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; + +},{"./errors":9,"./es5":10,"./util":21}],15:[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/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); +util.setReflectHandler(reflectHandler); + +var getDomain = function() { + var domain = process.domain; + if (domain === undefined) { + return null; + } + return domain; +}; +var getContextDefault = function() { + return null; +}; +var getContextDomain = function() { + return { + domain: getDomain(), + async: null + }; +}; +var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? + _dereq_("async_hooks").AsyncResource : null; +var getContextAsyncHooks = function() { + return { + domain: getDomain(), + async: new AsyncResource("Bluebird::Promise") + }; +}; +var getContext = util.isNode ? getContextDomain : getContextDefault; +util.notEnumerableProp(Promise, "_getContext", getContext); +var enableAsyncHooks = function() { + getContext = getContextAsyncHooks; + util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); +}; +var disableAsyncHooks = function() { + getContext = getContextDomain; + util.notEnumerableProp(Promise, "_getContext", getContextDomain); +}; + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = 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 = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; + +var debug = _dereq_("./debuggability")(Promise, Context, + enableAsyncHooks, disableAsyncHooks); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._resolveFromExecutor(executor); + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +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 (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("Catch statement predicate: " + + "expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + + if (typeof fn !== "function") { + throw new TypeError("The last argument to .catch() " + + "must be a function, got " + util.toString(fn)); + } + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && 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, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +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 () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + 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("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var context = getContext(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: util.contextBind(context, handler), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, + receiver, context); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + var bitField = this._bitField; + this._bitField = bitField | + (((bitField & 536870912) >> 2) ^ + 134217728); +}; + +Promise.prototype._setNoAsyncGuarantee = function() { + this._bitField = (this._bitField | 536870912) & + (~134217728); +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + context +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = util.contextBind(context, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + util.contextBind(context, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(maybePromise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + if (executor === INTERNAL) return; + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + 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._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + this._dereferenceTrace(); + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + es5.defineProperty(Promise.prototype, Symbol.toStringTag, { + get: function () { + return "Object"; + } + }); +} + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); +Promise.Promise = Promise; +Promise.version = "3.7.2"; + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = 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)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21,"async_hooks":undefined}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +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(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":21}],17:[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.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; + +},{}],18:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova)) && + ("classList" in document.documentElement)) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util":21}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = 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") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +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, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util":21}],21:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +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 typeof value === "function" || + typeof value === "object" && value !== null; +} + +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 FakeConstructor() {} + FakeConstructor.prototype = obj; + var receiver = new FakeConstructor(); + function ic() { + return typeof receiver.foo; + } + ic(); + ic(); + 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 isError(obj) { + return obj instanceof Error || + (obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"); +} + +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 isError(obj) && 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 asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if (classString(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } + + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } + + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var args = (new Array(2)).concat([].slice.call(arguments));; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; + } + return cb; +} + +var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + 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, + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + contextBind: contextBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); + } + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = _dereq_("async_hooks").AsyncResource; + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; + } + return supportsAsync; +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":10,"async_hooks":undefined}]},{},[3])(3) +}); ;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.core.min.js b/node_modules/bluebird/js/browser/bluebird.core.min.js new file mode 100644 index 0000000..836176e --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.core.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 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 3.7.2 + * Features enabled: core + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!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,n;return function r(t,e,n){function o(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[a]={exports:{}};t[a][0].call(u.exports,function(e){var n=t[a][1][e];return o(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var i="function"==typeof _dereq_&&_dereq_,a=0;a0;)c(t)}function c(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var n=t.shift(),r=t.shift();e.call(n,r)}}var l;try{throw new Error}catch(u){l=u}var p=t("./schedule"),f=t("./queue");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},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(n){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},r.prototype.invokeLater=o,r.prototype.invoke=i,r.prototype.settlePromises=a,r.prototype._drainQueues=function(){s(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,s(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=l},{"./queue":17,"./schedule":18}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var o=!1,i=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(i,i,null,this,t)},s=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(i){o||(o=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(i),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var f={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,a,void 0,u,f),l._then(s,c,void 0,u,f),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],3:[function(t,e,n){"use strict";function r(){try{Promise===i&&(Promise=o)}catch(t){}return i}var o;"undefined"!=typeof Promise&&(o=Promise);var i=t("./promise")();i.noConflict=r,e.exports=i},{"./promise":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,o){var i=t("./util"),a=i.tryCatch,s=i.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!o.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(i.isArray(t))for(var n=0;n=0?i[t]:void 0}var o=!1,i=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,i.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=i.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,i=t.prototype._popContext,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=i,t._peekContext=a,t.prototype._peekContext=s,t.prototype._promiseCreated=c,o=!1},o=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n,r,o){function i(t,e){return{promise:e}}function a(){return!1}function s(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+V.toString(t));r._attachCancellationCallback(t)})}catch(o){return o}}function c(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?V.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function l(){return this._onCancelField}function u(t){this._onCancelField=t}function p(){this._cancellationParent=void 0,this._onCancelField=void 0}function f(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function d(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function _(){this._trace=new H(this._peekContext())}function v(t,e){if(q(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=F(t);V.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),V.notEnumerableProp(t,"__stackCleaned__",!0)}}}function y(){this._trace=void 0}function g(t,e,n,r,o){if(void 0===t&&null!==e&&Z){if(void 0!==o&&o._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var i="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=E(s),l=c.length-1;l>=0;--l){var u=c[l];if(!M.test(u)){var p=u.match(W);p&&(i="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var f=c[0],l=0;l0&&(a="\n"+s[l-1]);break}}var h="a promise was created in a "+n+"handler "+i+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function m(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),b(n)}function b(t,n,r){if(ut.warnings){var o,i=new D(t);if(n)r._attachExtraTrace(i);else if(ut.longStackTraces&&(o=e._peekContext()))o.attachExtraTrace(i);else{var a=F(i);i.stack=a.message+"\n"+a.stack.join("\n")}it("warning",i)||T(i,"",!0)}}function C(t,e){for(var n=0;n=0;--s)if(r[s]===i){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[o]!==c)break;e.pop(),o--}e=r}}function E(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function F(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?j(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:E(e)}}function T(t,e,n){if("undefined"!=typeof console){var r;if(V.isObject(t)){var o=t.stack;r=e+z(o,t)}else r=e+String(t);"function"==typeof B?B(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function x(t,e,n,r){var o=!1;try{"function"==typeof e&&(o=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(i){I.throwLater(i)}"unhandledRejection"===t?it(t,n,r)||o||T(n,"Unhandled rejection "):it(t,r)}function R(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():V.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(o){}0===e.length&&(e="(empty array)")}return"(<"+S(e)+">, no stack trace)"}function S(t){var e=41;return t.lengtha||0>s||!n||!r||n!==r||a>=s||(st=function(t){if(G.test(t))return!0;var e=O(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function H(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);lt(this,H),e>32&&this.uncycle()}var N,L,B,U,I=e._async,D=t("./errors").Warning,V=t("./util"),Q=t("./es5"),q=V.canAttachTrace,G=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,M=/\((?:timers\.js):\d+:\d+\)/,W=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,$=null,z=null,X=!1,K=!(0==V.env("BLUEBIRD_DEBUG")||!V.env("BLUEBIRD_DEBUG")&&"development"!==V.env("NODE_ENV")),J=!(0==V.env("BLUEBIRD_WARNINGS")||!K&&!V.env("BLUEBIRD_WARNINGS")),Y=!(0==V.env("BLUEBIRD_LONG_STACK_TRACES")||!K&&!V.env("BLUEBIRD_LONG_STACK_TRACES")),Z=0!=V.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(J||!!V.env("BLUEBIRD_W_FORGOTTEN_RETURN"));!function(){function t(){for(var t=0;t0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return b(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var n=e._getContext();L=V.contextBind(n,t)},e.onUnhandledRejectionHandled=function(t){var n=e._getContext();N=V.contextBind(n,t)};var tt=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ut.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ut.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace,o=e.prototype._dereferenceTrace;ut.longStackTraces=!0,tt=function(){if(I.haveItemsQueued()&&!ut.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,e.prototype._dereferenceTrace=o,n.deactivateLongStackTraces(),ut.longStackTraces=!1},e.prototype._captureStackTrace=_,e.prototype._attachExtraTrace=v,e.prototype._dereferenceTrace=y,n.activateLongStackTraces()}},e.hasLongStackTraces=function(){return ut.longStackTraces&&P()};var et={unhandledrejection:{before:function(){var t=V.global.onunhandledrejection;return V.global.onunhandledrejection=null,t},after:function(t){V.global.onunhandledrejection=t}},rejectionhandled:{before:function(){var t=V.global.onrejectionhandled;return V.global.onrejectionhandled=null,t},after:function(t){V.global.onrejectionhandled=t}}},nt=function(){var t=function(t,e){if(!t)return!V.global.dispatchEvent(e);var n;try{return n=t.before(),!V.global.dispatchEvent(e)}finally{t.after(n)}};try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return V.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r={detail:n,cancelable:!0},o=new CustomEvent(e,r);return Q.defineProperty(o,"promise",{value:n.promise}),Q.defineProperty(o,"reason",{value:n.reason}),t(et[e],o)}}if("function"==typeof Event){var e=new Event("CustomEvent");return V.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r=new Event(e,{cancelable:!0});return r.detail=n,Q.defineProperty(r,"promise",{value:n.promise}),Q.defineProperty(r,"reason",{value:n.reason}),t(et[e],r)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),V.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r=document.createEvent("CustomEvent");return r.initCustomEvent(e,!1,!0,n),t(et[e],r)}}catch(n){}return function(){return!1}}(),rt=function(){return V.isNode?function(){return process.emit.apply(process,arguments)}:V.global?function(t){var e="on"+t.toLowerCase(),n=V.global[e];return n?(n.apply(V.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),ot={promiseCreated:i,promiseFulfilled:i,promiseRejected:i,promiseResolved:i,promiseCancelled:i,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:i},it=function(t){var e=!1;try{e=rt.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=nt(t,ot[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&tt()),"warnings"in t){var n=t.warnings;ut.warnings=!!n,Z=ut.warnings,V.isObject(n)&&"wForgottenReturn"in n&&(Z=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ut.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=p,e.prototype._propagateFrom=f,e.prototype._onCancel=l,e.prototype._setOnCancel=u,e.prototype._attachCancellationCallback=c,e.prototype._execute=s,at=f,ut.cancellation=!0}if("monitoring"in t&&(t.monitoring&&!ut.monitoring?(ut.monitoring=!0,e.prototype._fireEvent=it):!t.monitoring&&ut.monitoring&&(ut.monitoring=!1,e.prototype._fireEvent=a)),"asyncHooks"in t&&V.nodeSupportsAsyncResource){var i=ut.asyncHooks,h=!!t.asyncHooks;i!==h&&(ut.asyncHooks=h,h?r():o())}return e},e.prototype._fireEvent=a,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._dereferenceTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var at=h,st=function(){return!1},ct=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;V.inherits(H,Error),n.CapturedTrace=H,H.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,o=this;void 0!==o;++r)e.push(o),o=o._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var i=e[r].stack;void 0===n[i]&&(n[i]=r)}for(var r=0;t>r;++r){var a=e[r].stack,s=n[a];if(void 0!==s&&s!==r){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>s?(c._parent=e[s+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},H.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=F(t),n=e.message,r=[e.stack],o=this;void 0!==o;)r.push(E(o.stack.split("\n"))),o=o._parent;k(r),w(r),V.notEnumerableProp(t,"stack",C(n,r)),V.notEnumerableProp(t,"__stackCleaned__",!0)}};var lt=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():R(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,$=t,z=e;var n=Error.captureStackTrace;return st=function(t){return G.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return $=/@/,z=e,X=!0,function(t){t.stack=(new Error).stack};var o;try{throw new Error}catch(i){o="stack"in i}return"stack"in r||!o||"number"!=typeof Error.stackTraceLimit?(z=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?R(e):e.toString()},null):($=t,z=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(B=function(t){console.warn(t)},V.isNode&&process.stderr.isTTY?B=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:V.isNode||"string"!=typeof(new Error).stack||(B=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ut={warnings:J,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1};return Y&&e.longStackTraces(),{asyncHooks:function(){return ut.asyncHooks},longStackTraces:function(){return ut.longStackTraces},warnings:function(){return ut.warnings},cancellation:function(){return ut.cancellation},monitoring:function(){return ut.monitoring},propagateFromFunction:function(){return at},boundValueFunction:function(){return d},checkForgottenReturns:g,setBounds:A,warn:b,deprecated:m,CapturedTrace:H,fireDomEvent:nt,fireGlobalEvent:rt}}},{"./errors":9,"./es5":10,"./util":21}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var o=function(){return r};return this.caught(n,o)}}},{}],9:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function o(t){return this instanceof o?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new o(t)}var i,a,s=t("./es5"),c=s.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),d=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,a=RangeError}catch(v){i=r("TypeError","type error"),a=r("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;g1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return l.call(this,this.promise._target()._settledValue())}function c(t){return a(this,t)?void 0:(f.e=t,f)}function l(t){var o=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(o._boundValue()):l.call(o._boundValue(),t);if(u===r)return u;if(void 0!==u){o._setReturnedNonUndefined();var h=n(u,o);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var d=new p("late cancellation observer");return o._attachExtraTrace(d),f.e=d,f}h.isPending()&&h._attachCancellationCallback(new i(this))}return h._then(s,c,void 0,this,void 0)}}}return o.isRejected()?(a(this),f.e=t,f):(a(this),t)}var u=t("./util"),p=e.CancellationError,f=u.errorObj,h=t("./catch_filter")(r);return o.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){a(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new o(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,o=new Array(n-1),i=0;for(r=0;n-1>r;++r){var a=arguments[r];if(!u.isObject(a))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(a)));o[i++]=a}o.length=i;var s=arguments[r];return this._passThrough(h(o,s,this),1,void 0,l)},o}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,o,i){var a=t("./util");a.canEvaluate,a.tryCatch,a.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var o=[].slice.call(arguments);t&&o.pop();var r=new n(o).promise();return void 0!==t?r.spread(t):r}}},{"./util":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,o,i){var a=t("./util"),s=a.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+a.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var o=s(t).apply(this,arguments),a=r._popContext();return i.checkForgottenReturns(o,a,"Promise.method",r),r._resolveFromSyncValue(o),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return o("expecting a function but got "+a.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){i.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=a.isArray(l)?s(t).apply(u,l):s(t).call(u,l)}else c=s(t)();var p=r._popContext();return i.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===a.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":21}],14:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function o(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=u.keys(t),o=0;o1){var n,r=new Array(e-1),o=0; +for(n=0;e-1>n;++n){var i=arguments[n];if(!f.isObject(i))return u("Catch statement predicate: expecting an object but got "+f.classString(i));r[o++]=i}if(r.length=o,t=arguments[n],"function"!=typeof t)throw new j("The last argument to .catch() must be a function, got "+f.toString(t));return this.then(void 0,N(r,t,this))}return this.then(void 0,t)},o.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},o.prototype.then=function(t,e){if(A.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},o.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},o.prototype.spread=function(t){return"function"!=typeof t?u("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,x,void 0)},o.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},o.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new P(this).promise()},o.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},o.getNewLibraryCopy=e.exports,o.is=function(t){return t instanceof o},o.fromNode=o.fromCallback=function(t){var e=new o(T);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=U(t)(L(e,n));return r===B&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},o.all=function(t){return new P(t).promise()},o.cast=function(t){var e=S(t);return e instanceof o||(e=new o(T),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},o.resolve=o.fulfilled=o.cast,o.reject=o.rejected=function(t){var e=new o(T);return e._captureStackTrace(),e._rejectCallback(t,!0),e},o.setScheduler=function(t){if("function"!=typeof t)throw new j("expecting a function but got "+f.classString(t));return k.setScheduler(t)},o.prototype._then=function(t,e,n,r,i){var a=void 0!==i,s=a?i:new o(T),c=this._target(),l=c._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&l)?this._boundValue():c===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var u=g();if(0!==(50397184&l)){var p,h,d=c._settlePromiseCtx;0!==(33554432&l)?(h=c._rejectionHandler0,p=t):0!==(16777216&l)?(h=c._fulfillmentHandler0,p=e,c._unsetRejectionIsUnhandled()):(d=c._settlePromiseLateCancellationObserver,h=new F("late cancellation observer"),c._attachExtraTrace(h),p=e),k.invoke(d,c,{handler:f.contextBind(u,p),promise:s,receiver:r,value:h})}else c._addCallbacks(t,e,s,r,u);return s},o.prototype._length=function(){return 65535&this._bitField},o.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},o.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},o.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},o.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},o.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},o.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},o.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},o.prototype._isFinal=function(){return(4194304&this._bitField)>0},o.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},o.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},o.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},o.prototype._setAsyncGuaranteed=function(){if(!k.hasCustomScheduler()){var t=this._bitField;this._bitField=t|(536870912&t)>>2^134217728}},o.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&(536870912|this._bitField)},o.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===p?void 0:void 0===e&&this._isBound()?this._boundValue():e},o.prototype._promiseAt=function(t){return this[4*t-4+2]},o.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},o.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},o.prototype._boundValue=function(){},o.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,o=t._receiverAt(0);void 0===o&&(o=p),this._addCallbacks(e,n,r,o,null)},o.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),o=t._promiseAt(e),i=t._receiverAt(e);void 0===i&&(i=p),this._addCallbacks(n,r,o,i,null)},o.prototype._addCallbacks=function(t,e,n,r,o){var i=this._length();if(i>=65531&&(i=0,this._setLength(0)),0===i)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=f.contextBind(o,t)),"function"==typeof e&&(this._rejectionHandler0=f.contextBind(o,e));else{var a=4*i-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=f.contextBind(o,t)),"function"==typeof e&&(this[a+1]=f.contextBind(o,e))}return this._setLength(i+1),i},o.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},o.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=S(t,this);if(!(n instanceof o))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(c());var i=r._bitField;if(0===(50397184&i)){var a=this._length();a>0&&r._migrateCallback0(this);for(var s=1;a>s;++s)r._migrateCallbackAt(this,s);this._setFollowing(),this._setLength(0),this._setFollowee(n)}else if(0!==(33554432&i))this._fulfill(r._value());else if(0!==(16777216&i))this._reject(r._reason());else{var l=new F("late cancellation observer");r._attachExtraTrace(l),this._reject(l)}}},o.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),o=r===t;if(!o&&!n&&A.warnings()){var i="a promise was rejected with a non-error: "+f.classString(t);this._warn(i,!0)}this._attachExtraTrace(r,e?o:!1),this._reject(t)},o.prototype._resolveFromExecutor=function(t){if(t!==T){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},o.prototype._settlePromiseFromHandler=function(t,e,n,r){var o=r._bitField;if(0===(65536&o)){r._pushContext();var i;e===x?n&&"number"==typeof n.length?i=U(t).apply(this._boundValue(),n):(i=B,i.e=new j("cannot .spread() a non-array: "+f.classString(n))):i=U(t).call(e,n);var a=r._popContext();o=r._bitField,0===(65536&o)&&(i===R?r._reject(n):i===B?r._rejectCallback(i.e,!1):(A.checkForgottenReturns(i,a,"",r,this),r._resolveCallback(i)))}},o.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},o.prototype._followee=function(){return this._rejectionHandler0},o.prototype._setFollowee=function(t){this._rejectionHandler0=t},o.prototype._settlePromise=function(t,e,r,i){var a=t instanceof o,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof H&&r.isFinallyHandler()?(r.cancelPromise=t,U(e).call(r,i)===B&&t._reject(B.e)):e===l?t._fulfill(l.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof P?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,i,t)):e.call(r,i,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(i,t):r._promiseRejected(i,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?t._fulfill(i):t._reject(i))},o.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,i=t.value;"function"==typeof e?n instanceof o?this._settlePromiseFromHandler(e,r,i,n):e.call(r,i,n):n instanceof o&&n._reject(i)},o.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},o.prototype._settlePromise0=function(t,e,n){var r=this._promise0,o=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,o,e)},o.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},o.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():k.settlePromises(this),this._dereferenceTrace())}},o.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?k.fatalError(t,f.isNode):void((65535&e)>0?k.settlePromises(this):this._ensurePossibleRejectionHandled())},o.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),o=this._promiseAt(n),i=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(o,r,i,e)}},o.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),o=this._promiseAt(n),i=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(o,r,i,e)}},o.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},o.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&C.defineProperty(o.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),o.defer=o.pending=function(){A.deprecated("Promise.defer","new Promise");var t=new o(T);return{promise:t,resolve:i,reject:a}},f.notEnumerableProp(o,"_makeSelfResolutionError",c),t("./method")(o,T,S,u,A),t("./bind")(o,T,S,A),t("./cancel")(o,P,u,A),t("./direct_resolve")(o),t("./synchronous_inspection")(o),t("./join")(o,P,S,T,k),o.Promise=o,o.version="3.7.2",f.toFastProperties(o),f.toFastProperties(o.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new o(T)),A.setBounds(w.firstLineError,f.lastLineError),o}},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21,async_hooks:void 0}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,o,i){function a(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function s(t){var r=this._promise=new e(n);t instanceof e&&(r._propagateFrom(t,3),t.suppressUnhandledRejections()),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(s,i),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var i=r(this._values,this._promise);if(i instanceof e){i=i._target();var s=i._bitField;if(this._values=i,0===(50397184&s))return this._promise._setAsyncGuaranteed(),i._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(i._reason()):this._cancel();i=i._value()}if(i=c.asArray(i),null===i){var u=o("expecting an array or an iterable object but got "+c.classString(i)).reason();return void this._promise._rejectCallback(u,!1)}return 0===i.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(i)},s.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var o=this._promise,i=!1,a=null,s=0;n>s;++s){var c=r(t[s],o);c instanceof e?(c=c._target(),a=c._bitField):a=null,i?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):i=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):i=this._promiseFulfilled(c,s)}i||o._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;ni;++i)n[i+r]=t[i+e],t[i+e]=void 0}function o(t){this._capacity=t,this._length=0,this._front=0}o.prototype._willBeOverCapacity=function(t){return this._capacityn;++n)o[n]=t[n];return o[n]=e,o}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(i(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function f(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),o=A.test(t+"")&&F.names(t).length>0;if(n||r||o)return!0}return!1}catch(i){return!1}}function h(t){function e(){}function n(){return typeof r.foo}e.prototype=t;var r=new e;return n(),n(),t}function d(t){return H.test(t)}function _(t,e,n){for(var r=new Array(t),o=0;t>o;++o)r[o]=e+o+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{u(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function C(t){return{}.toString.call(t)}function w(t,e,n){for(var r=F.names(t),o=0;o10||t[0]>0}(),V.nodeSupportsAsyncResource=V.isNode&&function(){var e=!1;try{var n=t("async_hooks").AsyncResource;e="function"==typeof n.prototype.runInAsyncScope}catch(r){e=!1}return e}(),V.isNode&&V.toFastProperties(process);try{throw new Error}catch(Q){V.lastLineError=Q}e.exports=V},{"./es5":10,async_hooks:void 0}]},{},[3])(3)}),"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/browser/bluebird.js b/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..7f0686f --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5778 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 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 3.7.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!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) { + _drainQueueStep(queue); + } +} + +function _drainQueueStep(queue) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + } else { + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +} + +Async.prototype._drainQueues = function () { + _drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + _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 = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +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._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + 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, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; + +},{}],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")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise":22}],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"); +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 args = [].slice.call(arguments, 1);; + 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":36}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":36}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; + +},{}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var es5 = _dereq_("./es5"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); + } + + function unhandledRejectionClear() { + promises.length = 0; + } + + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; + + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + deferUnhandledRejectionCheck(this); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; + Context.deactivateLongStackTraces(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; + Context.activateLongStackTraces(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + + +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; + +var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); + } + } else { + return !util.global.dispatchEvent(e); + } + }; + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var eventData = { + detail: event, + cancelable: true + }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); + es5.defineProperty( + domEvent, "reason", {value: event.reason}); + + return dispatch(legacyHandlers[name], domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = new Event(name, { + cancelable: true + }); + domEvent.detail = event; + es5.defineProperty(domEvent, "promise", {value: event.promise}); + es5.defineProperty(domEvent, "reason", {value: event.reason}); + return dispatch(legacyHandlers[name], domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name, false, true, + event); + return dispatch(legacyHandlers[name], domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } + return Promise; +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._dereferenceTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (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 = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function longStackTracesDereferenceTrace() { + this._trace = undefined; +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", 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 = " (No stack trace)" === line || + stackFramePattern.test(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 && error.name != "SyntaxError") { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(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: error.name == "SyntaxError" ? stack : cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(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); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + 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 longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +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) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) 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; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +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.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = 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); +}; + +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 += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + 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 += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + 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; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false, + asyncHooks: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + asyncHooks: function() { + return config.asyncHooks; + }, + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; + +},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; +var PromiseAll = Promise.all; + +function promiseAllThis() { + return PromiseAll(this); +} + +function PromiseMapSeries(promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, INTERNAL); +} + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, this, undefined); +}; + +Promise.prototype.mapSeries = function (fn) { + return PromiseReduce(this, fn, INTERNAL, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, promises, undefined); +}; + +Promise.mapSeries = PromiseMapSeries; +}; + + +},{}],12:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util"); +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 + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5":13,"./util":36}],13:[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; + } + }; +} + +},{}],14:[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); +}; +}; + +},{}],15:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret === NEXT_FILTER) { + return ret; + } else if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; + +},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = _dereq_("./errors"); +var TypeError = errors.TypeError; +var util = _dereq_("./util"); +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) { + if (debug.cancellation()) { + var internal = new Promise(INTERNAL); + var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); + this._promise = internal.lastly(function() { + return _finallyPromise; + }); + internal._captureStackTrace(); + internal._setOnCancel(this); + } else { + 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; + this._yieldedPromise = null; + this._cancellationPhase = false; +} +util.inherits(PromiseSpawn, Proxyable); + +PromiseSpawn.prototype._isResolved = function() { + return this._promise === null; +}; + +PromiseSpawn.prototype._cleanup = function() { + this._promise = this._generator = null; + if (debug.cancellation() && this._finallyPromise !== null) { + this._finallyPromise._fulfill(); + this._finallyPromise = null; + } +}; + +PromiseSpawn.prototype._promiseCancelled = function() { + if (this._isResolved()) return; + var implementsReturn = typeof this._generator["return"] !== "undefined"; + + var result; + if (!implementsReturn) { + var reason = new Promise.CancellationError( + "generator .return() sentinel"); + Promise.coroutine.returnSentinel = reason; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + result = tryCatch(this._generator["throw"]).call(this._generator, + reason); + this._promise._popContext(); + } else { + this._promise._pushContext(); + result = tryCatch(this._generator["return"]).call(this._generator, + undefined); + this._promise._popContext(); + } + this._cancellationPhase = true; + this._yieldedPromise = null; + this._continue(result); +}; + +PromiseSpawn.prototype._promiseFulfilled = function(value) { + this._yieldedPromise = null; + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._promiseRejected = function(reason) { + this._yieldedPromise = null; + 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._resultCancelled = function() { + if (this._yieldedPromise instanceof Promise) { + var promise = this._yieldedPromise; + this._yieldedPromise = null; + promise.cancel(); + } +}; + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._promiseFulfilled(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + var promise = this._promise; + if (result === errorObj) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return promise._rejectCallback(result.e, false); + } + } + + var value = result.value; + if (result.done === true) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return 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._promiseRejected( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + this._yieldedPromise = maybePromise; + maybePromise._proxy(this, null); + } else if (((bitField & 33554432) !== 0)) { + Promise._async.invoke( + this._promiseFulfilled, this, maybePromise._value() + ); + } else if (((bitField & 16777216) !== 0)) { + Promise._async.invoke( + this._promiseRejected, this, maybePromise._reason() + ); + } else { + this._promiseCancelled(); + } + } +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\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); + var ret = spawn.promise(); + spawn._generator = generator; + spawn._promiseFulfilled(undefined); + return ret; + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + debug.deprecated("Promise.spawn()", "Promise.coroutine()"); + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; + +},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { +var util = _dereq_("./util"); +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 promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + 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 <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var context = Promise._getContext(); + holder.fn = util.contextBind(context, holder.fn); + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var args = [].slice.call(arguments);; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util":36}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var context = Promise._getContext(); + this._callback = util.contextBind(context, fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = []; + async.invoke(this._asyncInit, this, undefined); + if (util.isArray(promises)) { + for (var i = 0; i < promises.length; ++i) { + var maybePromise = promises[i]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + } +} +util.inherits(MappingPromiseArray, PromiseArray); + +MappingPromiseArray.prototype._asyncInit = function() { + 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 (index < 0) { + index = (index * -1) - 1; + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return true; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return false; + } + if (preservedValues !== null) preservedValues[index] = value; + + var promise = this._promise; + var callback = this._callback; + var receiver = promise._boundValue(); + promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); + if (ret === errorObj) { + this._reject(ret.e); + return true; + } + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + if (limit >= 1) this._inFlight++; + values[index] = maybePromise; + maybePromise._proxy(this, (index + 1) * -1); + return false; + } else if (((bitField & 33554432) !== 0)) { + ret = maybePromise._value(); + } else if (((bitField & 16777216) !== 0)) { + this._reject(maybePromise._reason()); + return true; + } else { + this._cancel(); + return true; + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + return true; + } + return false; +}; + +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) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + + var limit = 0; + if (options !== undefined) { + if (typeof options === "object" && options !== null) { + if (typeof options.concurrency !== "number") { + return Promise.reject( + new TypeError("'concurrency' must be a number but it is " + + util.classString(options.concurrency))); + } + limit = options.concurrency; + } else { + return Promise.reject(new TypeError( + "options argument must be an object but it is " + + util.classString(options))); + } + } + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter).promise(); +} + +Promise.prototype.map = function (fn, options) { + return map(this, fn, options, null); +}; + +Promise.map = function (promises, fn, options, _filter) { + return map(promises, fn, options, _filter); +}; + + +}; + +},{"./util":36}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util":36}],20:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors"); +var OperationalError = errors.OperationalError; +var es5 = _dereq_("./es5"); + +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, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; + +},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util"); +var async = Promise._async; +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 newReason = new Error(reason + ""); + 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; +}; +}; + +},{"./util":36}],22:[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/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); +util.setReflectHandler(reflectHandler); + +var getDomain = function() { + var domain = process.domain; + if (domain === undefined) { + return null; + } + return domain; +}; +var getContextDefault = function() { + return null; +}; +var getContextDomain = function() { + return { + domain: getDomain(), + async: null + }; +}; +var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? + _dereq_("async_hooks").AsyncResource : null; +var getContextAsyncHooks = function() { + return { + domain: getDomain(), + async: new AsyncResource("Bluebird::Promise") + }; +}; +var getContext = util.isNode ? getContextDomain : getContextDefault; +util.notEnumerableProp(Promise, "_getContext", getContext); +var enableAsyncHooks = function() { + getContext = getContextAsyncHooks; + util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); +}; +var disableAsyncHooks = function() { + getContext = getContextDomain; + util.notEnumerableProp(Promise, "_getContext", getContextDomain); +}; + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = 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 = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; + +var debug = _dereq_("./debuggability")(Promise, Context, + enableAsyncHooks, disableAsyncHooks); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._resolveFromExecutor(executor); + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +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 (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("Catch statement predicate: " + + "expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + + if (typeof fn !== "function") { + throw new TypeError("The last argument to .catch() " + + "must be a function, got " + util.toString(fn)); + } + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && 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, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +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 () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + 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("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var context = getContext(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: util.contextBind(context, handler), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, + receiver, context); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + var bitField = this._bitField; + this._bitField = bitField | + (((bitField & 536870912) >> 2) ^ + 134217728); +}; + +Promise.prototype._setNoAsyncGuarantee = function() { + this._bitField = (this._bitField | 536870912) & + (~134217728); +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + context +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = util.contextBind(context, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + util.contextBind(context, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(maybePromise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + if (executor === INTERNAL) return; + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + 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._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + this._dereferenceTrace(); + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + es5.defineProperty(Promise.prototype, Symbol.toStringTag, { + get: function () { + return "Object"; + } + }); +} + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); +Promise.Promise = Promise; +Promise.version = "3.7.2"; +_dereq_('./call_get.js')(Promise); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./nodeify.js')(Promise); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./settle.js')(Promise, PromiseArray, debug); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./timers.js')(Promise, INTERNAL, debug); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +_dereq_('./any.js')(Promise); +_dereq_('./each.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._promise0 = value; + p._receiver0 = 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)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,"async_hooks":undefined}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +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(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":36}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util"); +var nodebackForPromise = _dereq_("./nodeback"); +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/MqrFmX\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, _, multiArgs) { + 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"; + var body = "'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, " + multiArgs + "); \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\ + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode); + body = body.replace("Parameters", parameterDeclaration(newParameterCount)); + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL", + body)( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { + 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, multiArgs); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { + 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, multiArgs); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, + fn, suffix, multiArgs); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver, multiArgs) { + return makeNodePromisified(callback, receiver, undefined, + callback, null, multiArgs); +} + +Promise.promisify = function (fn, options) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + if (isPromisified(fn)) { + return fn; + } + options = Object(options); + var receiver = options.context === undefined ? THIS : options.context; + var multiArgs = !!options.multiArgs; + var ret = promisify(fn, receiver, multiArgs); + 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/MqrFmX\u000a"); + } + options = Object(options); + var multiArgs = !!options.multiArgs; + 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/MqrFmX\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, + multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); + } + } + + return promisifyAll(target, suffix, filter, promisifier, multiArgs); +}; +}; + + +},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util"); +var isObject = util.isObject; +var es5 = _dereq_("./es5"); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; + +var mapToEntries = (function() { + var index = 0; + var size = 0; + + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } + + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); + +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; + +function PropertiesPromiseArray(obj) { + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; + } + } + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, isMap ? -6 : -3); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () {}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val; + if (this._isMap) { + val = entriesToMap(this._values); + } else { + 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); + return true; + } + return false; +}; + +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/MqrFmX\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, 2); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; + +},{"./es5":13,"./util":36}],26:[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.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; + +},{}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util"); + +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 { + promises = util.asArray(promises); + if (promises === null) + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 3); + } + 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":36}],28:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var context = Promise._getContext(); + this._fn = util.contextBind(context, fn); + if (initialValue !== undefined) { + initialValue = Promise.resolve(initialValue); + initialValue._attachCancellationCallback(this); + } + this._initialValue = initialValue; + this._currentCancellable = null; + if(_each === INTERNAL) { + this._eachValues = Array(this._length); + } else if (_each === 0) { + this._eachValues = null; + } else { + this._eachValues = undefined; + } + this._promise._captureStackTrace(); + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._gotAccum = function(accum) { + if (this._eachValues !== undefined && + this._eachValues !== null && + accum !== INTERNAL) { + this._eachValues.push(accum); + } +}; + +ReductionPromiseArray.prototype._eachComplete = function(value) { + if (this._eachValues !== null) { + this._eachValues.push(value); + } + return this._eachValues; +}; + +ReductionPromiseArray.prototype._init = function() {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function() { + this._resolve(this._eachValues !== undefined ? this._eachValues + : this._initialValue); +}; + +ReductionPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +ReductionPromiseArray.prototype._resolve = function(value) { + this._promise._resolveCallback(value); + this._values = null; +}; + +ReductionPromiseArray.prototype._resultCancelled = function(sender) { + if (sender === this._initialValue) return this._cancel(); + if (this._isResolved()) return; + this._resultCancelled$(); + if (this._currentCancellable instanceof Promise) { + this._currentCancellable.cancel(); + } + if (this._initialValue instanceof Promise) { + this._initialValue.cancel(); + } +}; + +ReductionPromiseArray.prototype._iterate = function (values) { + this._values = values; + var value; + var i; + var length = values.length; + if (this._initialValue !== undefined) { + value = this._initialValue; + i = 0; + } else { + value = Promise.resolve(values[0]); + i = 1; + } + + this._currentCancellable = value; + + for (var j = i; j < length; ++j) { + var maybePromise = values[j]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + + if (!value.isRejected()) { + for (; i < length; ++i) { + var ctx = { + accum: null, + value: values[i], + index: i, + length: length, + array: this + }; + + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + + if ((i & 127) === 0) { + value._setNoAsyncGuarantee(); + } + } + } + + if (this._eachValues !== undefined) { + value = value + ._then(this._eachComplete, undefined, undefined, this, undefined); + } + value._then(completed, completed, undefined, value, this); +}; + +Promise.prototype.reduce = function (fn, initialValue) { + return reduce(this, fn, initialValue, null); +}; + +Promise.reduce = function (promises, fn, initialValue, _each) { + return reduce(promises, fn, initialValue, _each); +}; + +function completed(valueOrReason, array) { + if (this.isFulfilled()) { + array._resolve(valueOrReason); + } else { + array._reject(valueOrReason); + } +} + +function reduce(promises, fn, initialValue, _each) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var array = new ReductionPromiseArray(promises, fn, initialValue, _each); + return array.promise(); +} + +function gotAccum(accum) { + this.accum = accum; + this.array._gotAccum(accum); + var value = tryConvertToPromise(this.value, this.array._promise); + if (value instanceof Promise) { + this.array._currentCancellable = value; + return value._then(gotValue, undefined, undefined, this, undefined); + } else { + return gotValue.call(this, value); + } +} + +function gotValue(value) { + var array = this.array; + var promise = array._promise; + var fn = tryCatch(array._fn); + promise._pushContext(); + var ret; + if (array._eachValues !== undefined) { + ret = fn.call(promise._boundValue(), value, this.index, this.length); + } else { + ret = fn.call(promise._boundValue(), + this.accum, value, this.index, this.length); + } + if (ret instanceof Promise) { + array._currentCancellable = ret; + } + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", + promise + ); + return ret; +} +}; + +},{"./util":36}],29:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova)) && + ("classList" in document.documentElement)) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; + +},{"./util":36}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = + function(Promise, PromiseArray, debug) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 33554432; + ret._settledValueField = value; + return this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 16777216; + ret._settledValueField = reason; + return this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + debug.deprecated(".settle()", ".reflect()"); + return new SettledPromiseArray(promises).promise(); +}; + +Promise.allSettled = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return Promise.settle(this); +}; +}; + +},{"./util":36}],31:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util"); +var RangeError = _dereq_("./errors").RangeError; +var AggregateError = _dereq_("./errors").AggregateError; +var isArray = util.isArray; +var CANCELLATION = {}; + + +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); + } + return true; + } + return false; + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } + } + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; + } + return false; +}; + +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/MqrFmX\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":12,"./util":36}],32:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = 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") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +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, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util":36}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, debug) { +var util = _dereq_("./util"); +var TimeoutError = Promise.TimeoutError; + +function HandleWrapper(handle) { + this.handle = handle; +} + +HandleWrapper.prototype._resultCancelled = function() { + clearTimeout(this.handle); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (ms, value) { + var ret; + var handle; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + if (debug.cancellation() && value instanceof Promise) { + ret._setOnCancel(value); + } + } else { + ret = new Promise(INTERNAL); + handle = setTimeout(function() { ret._fulfill(); }, +ms); + if (debug.cancellation()) { + ret._setOnCancel(new HandleWrapper(handle)); + } + ret._captureStackTrace(); + } + ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.prototype.delay = function (ms) { + return delay(ms, this); +}; + +var afterTimeout = function (promise, message, parent) { + var err; + if (typeof message !== "string") { + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._reject(err); + + if (parent != null) { + parent.cancel(); + } +}; + +function successClear(value) { + clearTimeout(this.handle); + return value; +} + +function failureClear(reason) { + clearTimeout(this.handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret, parent; + + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { + if (ret.isPending()) { + afterTimeout(ret, message, parent); + } + }, ms)); + + if (debug.cancellation()) { + parent = this.then(); + ret = parent._then(successClear, failureClear, + undefined, handleWrapper, undefined); + ret._setOnCancel(handleWrapper); + } else { + ret = this._then(successClear, failureClear, + undefined, handleWrapper, undefined); + } + + return ret; +}; + +}; + +},{"./util":36}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext, INTERNAL, debug) { + var util = _dereq_("./util"); + var TypeError = _dereq_("./errors").TypeError; + var inherits = _dereq_("./util").inherits; + var errorObj = util.errorObj; + var tryCatch = util.tryCatch; + var NULL = {}; + + 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 = new Promise(INTERNAL); + function iterator() { + if (i >= len) return ret._fulfill(); + 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; + } + + 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; + } + + function ResourceList(length) { + this.length = length; + this.promise = null; + this[length-1] = null; + } + + ResourceList.prototype._resultCancelled = function() { + var len = this.length; + for (var i = 0; i < len; ++i) { + var item = this[i]; + if (item instanceof Promise) { + item.cancel(); + } + } + }; + + 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("expecting a function but got " + util.classString(fn)); + } + 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 ResourceList(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 reflectedResources = new Array(resources.length); + for (var i = 0; i < reflectedResources.length; ++i) { + reflectedResources[i] = Promise.resolve(resources[i]).reflect(); + } + + var resultPromise = Promise.all(reflectedResources) + .then(function(inspections) { + for (var i = 0; i < inspections.length; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + errorObj.e = inspection.error(); + return errorObj; + } else if (!inspection.isFulfilled()) { + resultPromise.cancel(); + return; + } + inspections[i] = inspection.value(); + } + promise._pushContext(); + + fn = tryCatch(fn); + var ret = spreadArgs + ? fn.apply(undefined, inspections) : fn(inspections); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promiseCreated, "Promise.using", promise); + return ret; + }); + + var promise = resultPromise.lastly(function() { + var inspection = new Promise.PromiseInspection(resultPromise); + return dispose(resources, inspection); + }); + resources.promise = promise; + promise._setOnCancel(resources); + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 131072; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 131072) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~131072); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +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 typeof value === "function" || + typeof value === "object" && value !== null; +} + +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 FakeConstructor() {} + FakeConstructor.prototype = obj; + var receiver = new FakeConstructor(); + function ic() { + return typeof receiver.foo; + } + ic(); + ic(); + 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 isError(obj) { + return obj instanceof Error || + (obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"); +} + +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 isError(obj) && 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 asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if (classString(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } + + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } + + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var args = (new Array(2)).concat([].slice.call(arguments));; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; + } + return cb; +} + +var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + 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, + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + contextBind: contextBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); + } + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = _dereq_("async_hooks").AsyncResource; + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; + } + return supportsAsync; +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":13,"async_hooks":undefined}]},{},[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..c1e907b --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2018 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 3.7.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!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,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var n=t[s][1][e];return i(n?n:e)},l,l.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;)c(t)}function c(t){var e=t.shift();if("function"!=typeof e)e._settlePromises();else{var n=t.shift(),r=t.shift();e.call(n,r)}}var u;try{throw new Error}catch(l){u=l}var p=t("./schedule"),f=t("./queue");r.prototype.setScheduler=function(t){var e=this._schedule;return this._schedule=t,this._customScheduler=!0,e},r.prototype.hasCustomScheduler=function(){return this._customScheduler},r.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues},r.prototype.fatalError=function(t,e){e?(process.stderr.write("Fatal "+(t instanceof Error?t.stack:t)+"\n"),process.exit(2)):this.throwLater(t)},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(n){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")}},r.prototype.invokeLater=i,r.prototype.invoke=o,r.prototype.settlePromises=s,r.prototype._drainQueues=function(){a(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,a(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=u},{"./queue":26,"./schedule":29}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var u=n(o),l=new t(e);l._propagateFrom(this,1);var p=this._target();if(l._setBoundTo(u),u instanceof t){var f={promiseRejectionQueued:!1,promise:l,target:p,bindingPromise:u};p._then(e,s,void 0,l,f),u._then(a,c,void 0,l,f),l._setOnCancel(u)}else l._resolveCallback(p);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.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"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){function o(t,e){return{promise:e}}function s(){return!1}function a(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+B.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function c(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?B.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function u(){return this._onCancelField}function l(t){this._onCancelField=t}function p(){this._cancellationParent=void 0,this._onCancelField=void 0}function f(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function _(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function d(){this._trace=new V(this._peekContext())}function v(t,e){if(q(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=F(t);B.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),B.notEnumerableProp(t,"__stackCleaned__",!0)}}}function y(){this._trace=void 0}function g(t,e,n,r,i){if(void 0===t&&null!==e&&Z){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),c=k(a),u=c.length-1;u>=0;--u){var l=c[u];if(!Q.test(l)){var p=l.match(G);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var f=c[0],u=0;u0&&(s="\n"+a[u-1]);break}}var h="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(h,!0,e)}}function m(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),b(n)}function b(t,n,r){if(lt.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(lt.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=F(o);o.stack=s.message+"\n"+s.stack.join("\n")}ot("warning",o)||x(o,"",!0)}}function w(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function k(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function F(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?E(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:k(e)}}function x(t,e,n){if("undefined"!=typeof console){var r;if(B.isObject(t)){var i=t.stack;r=e+X(i,t)}else r=e+String(t);"function"==typeof I?I(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function T(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){N.throwLater(o)}"unhandledRejection"===t?ot(t,n,r)||i||x(n,"Unhandled rejection "):ot(t,r)}function P(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():B.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+R(e)+">, no stack trace)"}function R(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(at=function(t){if($.test(t))return!0;var e=O(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function V(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);ut(this,V),e>32&&this.uncycle()}var H,D,I,L,N=e._async,U=t("./errors").Warning,B=t("./util"),M=t("./es5"),q=B.canAttachTrace,$=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,Q=/\((?:timers\.js):\d+:\d+\)/,G=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,z=null,X=null,W=!1,K=!(0==B.env("BLUEBIRD_DEBUG")||!B.env("BLUEBIRD_DEBUG")&&"development"!==B.env("NODE_ENV")),J=!(0==B.env("BLUEBIRD_WARNINGS")||!K&&!B.env("BLUEBIRD_WARNINGS")),Y=!(0==B.env("BLUEBIRD_LONG_STACK_TRACES")||!K&&!B.env("BLUEBIRD_LONG_STACK_TRACES")),Z=0!=B.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(J||!!B.env("BLUEBIRD_W_FORGOTTEN_RETURN"));!function(){function t(){for(var t=0;t0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return b(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var n=e._getContext();D=B.contextBind(n,t)},e.onUnhandledRejectionHandled=function(t){var n=e._getContext();H=B.contextBind(n,t)};var tt=function(){};e.longStackTraces=function(){if(N.haveItemsQueued()&&!lt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!lt.longStackTraces&&S()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace,i=e.prototype._dereferenceTrace;lt.longStackTraces=!0,tt=function(){if(N.haveItemsQueued()&&!lt.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,e.prototype._dereferenceTrace=i,n.deactivateLongStackTraces(),lt.longStackTraces=!1},e.prototype._captureStackTrace=d,e.prototype._attachExtraTrace=v,e.prototype._dereferenceTrace=y,n.activateLongStackTraces()}},e.hasLongStackTraces=function(){return lt.longStackTraces&&S()};var et={unhandledrejection:{before:function(){var t=B.global.onunhandledrejection;return B.global.onunhandledrejection=null,t},after:function(t){B.global.onunhandledrejection=t}},rejectionhandled:{before:function(){var t=B.global.onrejectionhandled;return B.global.onrejectionhandled=null,t},after:function(t){B.global.onrejectionhandled=t}}},nt=function(){var t=function(t,e){if(!t)return!B.global.dispatchEvent(e);var n;try{return n=t.before(),!B.global.dispatchEvent(e)}finally{t.after(n)}};try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return B.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r={detail:n,cancelable:!0},i=new CustomEvent(e,r);return M.defineProperty(i,"promise",{value:n.promise}),M.defineProperty(i,"reason",{value:n.reason}),t(et[e],i)}}if("function"==typeof Event){var e=new Event("CustomEvent");return B.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r=new Event(e,{cancelable:!0});return r.detail=n,M.defineProperty(r,"promise",{value:n.promise}),M.defineProperty(r,"reason",{value:n.reason}),t(et[e],r)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),B.global.dispatchEvent(e),function(e,n){e=e.toLowerCase();var r=document.createEvent("CustomEvent");return r.initCustomEvent(e,!1,!0,n),t(et[e],r)}}catch(n){}return function(){return!1}}(),rt=function(){return B.isNode?function(){return process.emit.apply(process,arguments)}:B.global?function(t){var e="on"+t.toLowerCase(),n=B.global[e];return n?(n.apply(B.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),it={promiseCreated:o,promiseFulfilled:o,promiseRejected:o,promiseResolved:o,promiseCancelled:o,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:o},ot=function(t){var e=!1;try{e=rt.apply(null,arguments)}catch(n){N.throwLater(n),e=!0}var r=!1;try{r=nt(t,it[t].apply(null,arguments))}catch(n){N.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&tt()),"warnings"in t){var n=t.warnings;lt.warnings=!!n,Z=lt.warnings,B.isObject(n)&&"wForgottenReturn"in n&&(Z=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!lt.cancellation){if(N.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=p,e.prototype._propagateFrom=f,e.prototype._onCancel=u,e.prototype._setOnCancel=l,e.prototype._attachCancellationCallback=c,e.prototype._execute=a,st=f,lt.cancellation=!0}if("monitoring"in t&&(t.monitoring&&!lt.monitoring?(lt.monitoring=!0,e.prototype._fireEvent=ot):!t.monitoring&<.monitoring&&(lt.monitoring=!1,e.prototype._fireEvent=s)),"asyncHooks"in t&&B.nodeSupportsAsyncResource){var o=lt.asyncHooks,h=!!t.asyncHooks;o!==h&&(lt.asyncHooks=h,h?r():i())}return e},e.prototype._fireEvent=s,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._dereferenceTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var st=h,at=function(){return!1},ct=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;B.inherits(V,Error),n.CapturedTrace=V,V.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var u=c._length+1,l=r-2;l>=0;--l)e[l]._length=u,u++;return}}}},V.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=F(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(k(i.stack.split("\n"))),i=i._parent;j(r),C(r),B.notEnumerableProp(t,"stack",w(n,r)),B.notEnumerableProp(t,"__stackCleaned__",!0)}};var ut=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():P(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,z=t,X=e;var n=Error.captureStackTrace;return at=function(t){return $.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return z=/@/,X=e,W=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(X=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?P(e):e.toString()},null):(z=t,X=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(I=function(t){console.warn(t)},B.isNode&&process.stderr.isTTY?I=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:B.isNode||"string"!=typeof(new Error).stack||(I=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var lt={warnings:J,longStackTraces:!1,cancellation:!1,monitoring:!1,asyncHooks:!1};return Y&&e.longStackTraces(),{asyncHooks:function(){return lt.asyncHooks},longStackTraces:function(){return lt.longStackTraces},warnings:function(){return lt.warnings},cancellation:function(){return lt.cancellation},monitoring:function(){return lt.monitoring},propagateFromFunction:function(){return st},boundValueFunction:function(){return _},checkForgottenReturns:g,setBounds:A,warn:b,deprecated:m,CapturedTrace:V,fireDomEvent:nt,fireGlobalEvent:rt}}},{"./errors":12,"./es5":13,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return i(this,t,e,0)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,r){return i(t,r,e,0)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return l(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,u=t("./util"),l=u.inherits,p=u.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("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;g1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return u.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(f.e=t,f)}function u(t){var i=this.promise,u=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?u.call(i._boundValue()):u.call(i._boundValue(),t);if(l===r)return l;if(void 0!==l){i._setReturnedNonUndefined();var h=n(l,i);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),f.e=_,f}h.isPending()&&h._attachCancellationCallback(new o(this))}return h._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),f.e=t,f):(s(this),t)}var l=t("./util"),p=e.CancellationError,f=l.errorObj,h=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,u,u)},e.prototype.tap=function(t){return this._passThrough(t,1,u)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,u);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!l.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+l.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(h(i,a,this),1,void 0,u)},i}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t),this._promise._captureStackTrace();var s=e._getContext();if(this._callback=u.contextBind(s,n),this._preservedValues=i===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0),u.isArray(t))for(var a=0;a=1?s:0,new a(t,n,s,o).promise()}var u=t("./util"),l=u.tryCatch,p=u.errorObj,f=e._async;u.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var u=this._promise,f=this._callback,h=u._boundValue();u._pushContext();var _=l(f).call(h,t,n,o),d=u._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",u),_===p)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var g=++this._totalResolved;return g>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var u=arguments[1],l=arguments[2];c=s.isArray(u)?a(t).apply(l,u):a(t).call(l,u)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&l.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new u(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=l.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!f.isObject(o))return l("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}if(r.length=i,t=arguments[n],"function"!=typeof t)throw new E("The last argument to .catch() must be a function, got "+f.toString(t));return this.then(void 0,D(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(V.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?l("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,T,void 0)},i.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},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new S(this).promise()},i.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(x);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=N(t)(I(e,n));return r===L&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new S(t).promise()},i.cast=function(t){var e=R(t);return e instanceof i||(e=new i(x),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(x);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new E("expecting a function but got "+f.classString(t));return j.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(x),c=this._target(),u=c._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():c===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var l=g();if(0!==(50397184&u)){var p,h,_=c._settlePromiseCtx;0!==(33554432&u)?(h=c._rejectionHandler0,p=t):0!==(16777216&u)?(h=c._fulfillmentHandler0,p=e,c._unsetRejectionIsUnhandled()):(_=c._settlePromiseLateCancellationObserver,h=new F("late cancellation observer"),c._attachExtraTrace(h),p=e),j.invoke(_,c,{handler:f.contextBind(l,p),promise:a,receiver:r,value:h})}else c._addCallbacks(t,e,a,r,l);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){if(!j.hasCustomScheduler()){var t=this._bitField;this._bitField=t|(536870912&t)>>2^134217728}},i.prototype._setNoAsyncGuarantee=function(){this._bitField=-134217729&(536870912|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===p?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=p),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=p),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=f.contextBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=f.contextBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=f.contextBind(i,t)),"function"==typeof e&&(this[s+1]=f.contextBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=R(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(c());var o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(n)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var u=new F("late cancellation observer");r._attachExtraTrace(u),this._reject(u)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&V.warnings()){var o="a promise was rejected with a non-error: "+f.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==x){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===T?n&&"number"==typeof n.length?o=N(t).apply(this._boundValue(),n):(o=L,o.e=new E("cannot .spread() a non-array: "+f.classString(n))):o=N(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===P?r._reject(n):o===L?r._rejectCallback(o.e,!1):(V.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),r instanceof H&&r.isFinallyHandler()?(r.cancelPromise=t,N(e).call(r,o)===L&&t._reject(L.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof S?t._cancel():r.cancel()):"function"==typeof e?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():j.settlePromises(this),this._dereferenceTrace())}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?j.fatalError(t,f.isNode):void((65535&e)>0?j.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},"undefined"!=typeof Symbol&&Symbol.toStringTag&&w.defineProperty(i.prototype,Symbol.toStringTag,{get:function(){return"Object"}}),i.defer=i.pending=function(){V.deprecated("Promise.defer","new Promise");var t=new i(x);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",c),t("./method")(i,x,R,l,V),t("./bind")(i,x,R,V),t("./cancel")(i,S,l,V),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,S,R,x,j),i.Promise=i,i.version="3.7.2",t("./call_get.js")(i),t("./generators.js")(i,l,x,R,n,V),t("./map.js")(i,S,l,R,x,V),t("./nodeify.js")(i),t("./promisify.js")(i,x),t("./props.js")(i,S,R,l),t("./race.js")(i,x,R,l),t("./reduce.js")(i,S,l,R,x,V),t("./settle.js")(i,S,V),t("./some.js")(i,S,l),t("./timers.js")(i,x,V),t("./using.js")(i,l,R,A,x,V),t("./any.js")(i),t("./each.js")(i,x),t("./filter.js")(i,x),f.toFastProperties(i),f.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(x)),V.setBounds(C.firstLineError,f.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36,async_hooks:void 0}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function a(t){var r=this._promise=new e(n);t instanceof e&&(r._propagateFrom(t,3),t.suppressUnhandledRejections()),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function u(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(u,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var l=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(l,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nc;c+=2){var l=s[c],p=s[c+1],_=l+e;if(r===E)t[_]=E(l,f,l,p,e,i);else{var d=r(p,function(){return E(l,f,l,p,e,i)});h.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return h.toFastProperties(t),t}function l(t,e,n){return E(t,e,void 0,t,null,n)}var p,f={},h=t("./util"),_=t("./nodeback"),d=h.withAppended,v=h.maybeWrapAsError,y=h.canEvaluate,g=t("./errors").TypeError,m="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return h.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},k=function(t){return t.replace(/([$])/,"\\$")},E=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?f:e.context,o=!!e.multiArgs,s=l(t,n,o);return h.copyDescriptors(t,s,r),s},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/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=m);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=E),!h.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=h.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function s(t){var n,s=r(t);return u(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),u=c.isObject,l=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),f=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=f(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},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":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=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._capacityf;++f){var _=t[f];(void 0!==_||f in t)&&e.cast(_)._then(l,p,void 0,u,null)}return u}var s=t("./util"),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":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=e._getContext();this._fn=f.contextBind(s,n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,i===o?this._eachValues=Array(this._length):0===i?this._eachValues=null:this._eachValues=void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function u(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function l(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=h(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var f=t("./util"),h=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n;for(var o=r;i>o;++o){var s=t[o];s instanceof e&&s.suppressUnhandledRejections()}if(!n.isRejected())for(;i>r;++r){var a={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(l,void 0,void 0,a,void 0),0===(127&r)&&n._setNoAsyncGuarantee()}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,n,r){return u(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s&&"function"==typeof s.resolve){ +var u=s.resolve();r=function(t){u.then(t)}}else r="undefined"!=typeof MutationObserver&&("undefined"==typeof window||!window.navigator||!window.navigator.standalone&&!window.cordova)&&"classList"in document.documentElement?function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}():"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o;e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.allSettled=function(t){return new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){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 r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,u=s.isArray,l={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=u(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){return 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),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(l(t)){if(t instanceof e)return t;var i=o(t);if(i===u){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return u.e=e,u}}function s(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),l=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,f=c.tryCatch(r).call(t,o,s);return p=!1,a&&f===u&&(a._rejectCallback(f.e,!0,!0),a=null),l}var c=t("./util"),u=c.errorObj,l=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var u=function(t){return l(+this).thenReturn(t)},l=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(u,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return l(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,n){function i(){if(s>=u)return l._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,u=t.length,l=new e(o);return i(),l}function l(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function f(t){return l.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function h(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,g=_.tryCatch,m={};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():m},l.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==m?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},l.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,l),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},h.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new h(t),p=0;t>p;++p){var d=o[p];if(l.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var m=r(d);m instanceof e&&(d=m._then(f,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=P;return P=null,t.apply(this,arguments)}catch(e){return T.e=e,T}}function i(t){return P=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function u(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function l(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function f(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function h(t){function e(){}function n(){return typeof r.foo}e.prototype=t;var r=new e;return n(),n(),t}function _(t){return V.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{l(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i10||t[0]>0}(),B.nodeSupportsAsyncResource=B.isNode&&function(){var e=!1;try{var n=t("async_hooks").AsyncResource;e="function"==typeof n.prototype.runInAsyncScope}catch(r){e=!1}return e}(),B.isNode&&B.toFastProperties(process);try{throw new Error}catch(M){B.lastLineError=M}e.exports=B},{"./es5":13,async_hooks:void 0}]},{},[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/release/any.js b/node_modules/bluebird/js/release/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/node_modules/bluebird/js/release/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/bluebird/js/release/assert.js b/node_modules/bluebird/js/release/assert.js new file mode 100644 index 0000000..4518231 --- /dev/null +++ b/node_modules/bluebird/js/release/assert.js @@ -0,0 +1,55 @@ +"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(Math.max($_len - 2, 0)); 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); + } + throw ret; +}; +})(); diff --git a/node_modules/bluebird/js/release/async.js b/node_modules/bluebird/js/release/async.js new file mode 100644 index 0000000..8eab6f8 --- /dev/null +++ b/node_modules/bluebird/js/release/async.js @@ -0,0 +1,120 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule"); +var Queue = require("./queue"); + +function Async() { + this._customScheduler = false; + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._haveDrainedQueues = false; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = schedule; +} + +Async.prototype.setScheduler = function(fn) { + var prev = this._schedule; + this._schedule = fn; + this._customScheduler = true; + return prev; +}; + +Async.prototype.hasCustomScheduler = function() { + return this._customScheduler; +}; + +Async.prototype.haveItemsQueued = function () { + return this._isTickUsed || this._haveDrainedQueues; +}; + + +Async.prototype.fatalError = function(e, isNode) { + if (isNode) { + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + + "\n"); + process.exit(2); + } else { + this.throwLater(e); + } +}; + +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/MqrFmX\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(); +} + +Async.prototype.invokeLater = AsyncInvokeLater; +Async.prototype.invoke = AsyncInvoke; +Async.prototype.settlePromises = AsyncSettlePromises; + + +function _drainQueue(queue) { + while (queue.length() > 0) { + _drainQueueStep(queue); + } +} + +function _drainQueueStep(queue) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + } else { + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +} + +Async.prototype._drainQueues = function () { + _drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + _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 = Async; +module.exports.firstLineError = firstLineError; diff --git a/node_modules/bluebird/js/release/bind.js b/node_modules/bluebird/js/release/bind.js new file mode 100644 index 0000000..fc3379d --- /dev/null +++ b/node_modules/bluebird/js/release/bind.js @@ -0,0 +1,67 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +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._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + 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, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; diff --git a/node_modules/bluebird/js/release/bluebird.js b/node_modules/bluebird/js/release/bluebird.js new file mode 100644 index 0000000..1c36cf3 --- /dev/null +++ b/node_modules/bluebird/js/release/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")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/bluebird/js/release/call_get.js b/node_modules/bluebird/js/release/call_get.js new file mode 100644 index 0000000..0ed7714 --- /dev/null +++ b/node_modules/bluebird/js/release/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"); +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(Math.max($_len - 1, 0)); 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/release/cancel.js b/node_modules/bluebird/js/release/cancel.js new file mode 100644 index 0000000..7a12415 --- /dev/null +++ b/node_modules/bluebird/js/release/cancel.js @@ -0,0 +1,129 @@ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise._isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent._isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + promise._setWillBeCancelled(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this._isCancellable()) return; + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this._isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; diff --git a/node_modules/bluebird/js/release/catch_filter.js b/node_modules/bluebird/js/release/catch_filter.js new file mode 100644 index 0000000..0f24ce2 --- /dev/null +++ b/node_modules/bluebird/js/release/catch_filter.js @@ -0,0 +1,42 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util"); +var getKeys = require("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; diff --git a/node_modules/bluebird/js/release/context.js b/node_modules/bluebird/js/release/context.js new file mode 100644 index 0000000..c307414 --- /dev/null +++ b/node_modules/bluebird/js/release/context.js @@ -0,0 +1,69 @@ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; diff --git a/node_modules/bluebird/js/release/debuggability.js b/node_modules/bluebird/js/release/debuggability.js new file mode 100644 index 0000000..ce997ee --- /dev/null +++ b/node_modules/bluebird/js/release/debuggability.js @@ -0,0 +1,1009 @@ +"use strict"; +module.exports = function(Promise, Context, + enableAsyncHooks, disableAsyncHooks) { +var async = Promise._async; +var Warning = require("./errors").Warning; +var util = require("./util"); +var es5 = require("./es5"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; +var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (false || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); + +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); + +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && + (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + +var deferUnhandledRejectionCheck; +(function() { + var promises = []; + + function unhandledRejectionCheck() { + for (var i = 0; i < promises.length; ++i) { + promises[i]._notifyUnhandledRejection(); + } + unhandledRejectionClear(); + } + + function unhandledRejectionClear() { + promises.length = 0; + } + + deferUnhandledRejectionCheck = function(promise) { + promises.push(promise); + setTimeout(unhandledRejectionCheck, 1); + }; + + es5.defineProperty(Promise, "_unhandledRejectionCheck", { + value: unhandledRejectionCheck + }); + es5.defineProperty(Promise, "_unhandledRejectionClear", { + value: unhandledRejectionClear + }); +})(); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 524288); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 524288) !== 0) return; + this._setRejectionIsUnhandled(); + deferUnhandledRejectionCheck(this); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._setReturnedNonUndefined = function() { + this._bitField = this._bitField | 268435456; +}; + +Promise.prototype._returnedNonUndefined = function() { + return (this._bitField & 268435456) !== 0; +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var context = Promise._getContext(); + possiblyUnhandledRejection = util.contextBind(context, fn); +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var context = Promise._getContext(); + unhandledRejectionHandled = util.contextBind(context, fn); +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; + Context.deactivateLongStackTraces(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; + Context.activateLongStackTraces(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + + +var legacyHandlers = { + unhandledrejection: { + before: function() { + var ret = util.global.onunhandledrejection; + util.global.onunhandledrejection = null; + return ret; + }, + after: function(fn) { + util.global.onunhandledrejection = fn; + } + }, + rejectionhandled: { + before: function() { + var ret = util.global.onrejectionhandled; + util.global.onrejectionhandled = null; + return ret; + }, + after: function(fn) { + util.global.onrejectionhandled = fn; + } + } +}; + +var fireDomEvent = (function() { + var dispatch = function(legacy, e) { + if (legacy) { + var fn; + try { + fn = legacy.before(); + return !util.global.dispatchEvent(e); + } finally { + legacy.after(fn); + } + } else { + return !util.global.dispatchEvent(e); + } + }; + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var eventData = { + detail: event, + cancelable: true + }; + var domEvent = new CustomEvent(name, eventData); + es5.defineProperty( + domEvent, "promise", {value: event.promise}); + es5.defineProperty( + domEvent, "reason", {value: event.reason}); + + return dispatch(legacyHandlers[name], domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = new Event(name, { + cancelable: true + }); + domEvent.detail = event; + es5.defineProperty(domEvent, "promise", {value: event.promise}); + es5.defineProperty(domEvent, "reason", {value: event.reason}); + return dispatch(legacyHandlers[name], domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + name = name.toLowerCase(); + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name, false, true, + event); + return dispatch(legacyHandlers[name], domEvent); + }; + } + } catch (e) {} + return function() { + return false; + }; +})(); + +var fireGlobalEvent = (function() { + if (util.isNode) { + return function() { + return process.emit.apply(process, arguments); + }; + } else { + if (!util.global) { + return function() { + return false; + }; + } + return function(name) { + var methodName = "on" + name.toLowerCase(); + var method = util.global[methodName]; + if (!method) return false; + method.apply(util.global, [].slice.call(arguments, 1)); + return true; + }; + } +})(); + +function generatePromiseLifecycleEventObject(name, promise) { + return {promise: promise}; +} + +var eventToObjectGenerator = { + promiseCreated: generatePromiseLifecycleEventObject, + promiseFulfilled: generatePromiseLifecycleEventObject, + promiseRejected: generatePromiseLifecycleEventObject, + promiseResolved: generatePromiseLifecycleEventObject, + promiseCancelled: generatePromiseLifecycleEventObject, + promiseChained: function(name, promise, child) { + return {promise: promise, child: child}; + }, + warning: function(name, warning) { + return {warning: warning}; + }, + unhandledRejection: function (name, reason, promise) { + return {reason: reason, promise: promise}; + }, + rejectionHandled: generatePromiseLifecycleEventObject +}; + +var activeFireEvent = function (name) { + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent.apply(null, arguments); + } catch (e) { + async.throwLater(e); + globalEventFired = true; + } + + var domEventFired = false; + try { + domEventFired = fireDomEvent(name, + eventToObjectGenerator[name].apply(null, arguments)); + } catch (e) { + async.throwLater(e); + domEventFired = true; + } + + return domEventFired || globalEventFired; +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + var warningsOption = opts.warnings; + config.warnings = !!warningsOption; + wForgottenReturn = config.warnings; + + if (util.isObject(warningsOption)) { + if ("wForgottenReturn" in warningsOption) { + wForgottenReturn = !!warningsOption.wForgottenReturn; + } + } + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } + if ("monitoring" in opts) { + if (opts.monitoring && !config.monitoring) { + config.monitoring = true; + Promise.prototype._fireEvent = activeFireEvent; + } else if (!opts.monitoring && config.monitoring) { + config.monitoring = false; + Promise.prototype._fireEvent = defaultFireEvent; + } + } + if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) { + var prev = config.asyncHooks; + var cur = !!opts.asyncHooks; + if (prev !== cur) { + config.asyncHooks = cur; + if (cur) { + enableAsyncHooks(); + } else { + disableAsyncHooks(); + } + } + } + return Promise; +}; + +function defaultFireEvent() { return false; } + +Promise.prototype._fireEvent = defaultFireEvent; +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._dereferenceTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this._isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (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 = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function longStackTracesDereferenceTrace() { + this._trace = undefined; +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise, + parent) { + if (returnValue === undefined && promiseCreated !== null && + wForgottenReturn) { + if (parent !== undefined && parent._returnedNonUndefined()) return; + if ((promise._bitField & 65535) === 0) return; + + if (name) name = name + " "; + var handlerLine = ""; + var creatorLine = ""; + if (promiseCreated._trace) { + var traceLines = promiseCreated._trace.stack.split("\n"); + var stack = cleanStack(traceLines); + for (var i = stack.length - 1; i >= 0; --i) { + var line = stack[i]; + if (!nodeFramePattern.test(line)) { + var lineMatches = line.match(parseLinePattern); + if (lineMatches) { + handlerLine = "at " + lineMatches[1] + + ":" + lineMatches[2] + ":" + lineMatches[3] + " "; + } + break; + } + } + + if (stack.length > 0) { + var firstUserLine = stack[0]; + for (var i = 0; i < traceLines.length; ++i) { + + if (traceLines[i] === firstUserLine) { + if (i > 0) { + creatorLine = "\n" + traceLines[i - 1]; + } + break; + } + } + + } + } + var msg = "a promise was created in a " + name + + "handler " + handlerLine + "but was not returned from it, " + + "see http://goo.gl/rRqMUw" + + creatorLine; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + + if (!activeFireEvent("warning", warning)) { + formatAndLogError(warning, "", 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 = " (No stack trace)" === line || + stackFramePattern.test(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 && error.name != "SyntaxError") { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(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: error.name == "SyntaxError" ? stack : cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(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); + } + + if (name === "unhandledRejection") { + if (!activeFireEvent(name, reason, promise) && !localEventFired) { + formatAndLogError(reason, "Unhandled rejection "); + } + } else { + activeFireEvent(name, promise); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + 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 longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +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) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) 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; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +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.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = 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); +}; + +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 += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + 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 += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + 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; + +})([]); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false, + monitoring: false, + asyncHooks: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + asyncHooks: function() { + return config.asyncHooks; + }, + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + monitoring: function() { + return config.monitoring; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace, + fireDomEvent: fireDomEvent, + fireGlobalEvent: fireGlobalEvent +}; +}; diff --git a/node_modules/bluebird/js/release/direct_resolve.js b/node_modules/bluebird/js/release/direct_resolve.js new file mode 100644 index 0000000..a890298 --- /dev/null +++ b/node_modules/bluebird/js/release/direct_resolve.js @@ -0,0 +1,46 @@ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; diff --git a/node_modules/bluebird/js/release/each.js b/node_modules/bluebird/js/release/each.js new file mode 100644 index 0000000..e4f3d05 --- /dev/null +++ b/node_modules/bluebird/js/release/each.js @@ -0,0 +1,30 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; +var PromiseAll = Promise.all; + +function promiseAllThis() { + return PromiseAll(this); +} + +function PromiseMapSeries(promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, INTERNAL); +} + +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, this, undefined); +}; + +Promise.prototype.mapSeries = function (fn) { + return PromiseReduce(this, fn, INTERNAL, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, 0) + ._then(promiseAllThis, undefined, undefined, promises, undefined); +}; + +Promise.mapSeries = PromiseMapSeries; +}; + diff --git a/node_modules/bluebird/js/release/errors.js b/node_modules/bluebird/js/release/errors.js new file mode 100644 index 0000000..f62f323 --- /dev/null +++ b/node_modules/bluebird/js/release/errors.js @@ -0,0 +1,116 @@ +"use strict"; +var es5 = require("./es5"); +var Objectfreeze = es5.freeze; +var util = require("./util"); +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 + }); + es5.defineProperty(Error, "__BluebirdErrorTypes__", { + value: errorTypes, + writable: false, + enumerable: false, + configurable: false + }); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; diff --git a/node_modules/bluebird/js/release/es5.js b/node_modules/bluebird/js/release/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/bluebird/js/release/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/release/filter.js b/node_modules/bluebird/js/release/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/bluebird/js/release/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/release/finally.js b/node_modules/bluebird/js/release/finally.js new file mode 100644 index 0000000..d57444b --- /dev/null +++ b/node_modules/bluebird/js/release/finally.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = require("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = require("./catch_filter")(NEXT_FILTER); + +function PassThroughHandlerContext(promise, type, handler) { + this.promise = promise; + this.type = type; + this.handler = handler; + this.called = false; + this.cancelPromise = null; +} + +PassThroughHandlerContext.prototype.isFinallyHandler = function() { + return this.type === 0; +}; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.isFinallyHandler() + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret === NEXT_FILTER) { + return ret; + } else if (ret !== undefined) { + promise._setReturnedNonUndefined(); + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise._isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, + fail, + undefined, + new PassThroughHandlerContext(this, type, handler), + undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + var catchInstances = new Array(len - 1), + j = 0, i; + for (i = 0; i < len - 1; ++i) { + var item = arguments[i]; + if (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; diff --git a/node_modules/bluebird/js/release/generators.js b/node_modules/bluebird/js/release/generators.js new file mode 100644 index 0000000..500c280 --- /dev/null +++ b/node_modules/bluebird/js/release/generators.js @@ -0,0 +1,223 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = require("./errors"); +var TypeError = errors.TypeError; +var util = require("./util"); +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) { + if (debug.cancellation()) { + var internal = new Promise(INTERNAL); + var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); + this._promise = internal.lastly(function() { + return _finallyPromise; + }); + internal._captureStackTrace(); + internal._setOnCancel(this); + } else { + 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; + this._yieldedPromise = null; + this._cancellationPhase = false; +} +util.inherits(PromiseSpawn, Proxyable); + +PromiseSpawn.prototype._isResolved = function() { + return this._promise === null; +}; + +PromiseSpawn.prototype._cleanup = function() { + this._promise = this._generator = null; + if (debug.cancellation() && this._finallyPromise !== null) { + this._finallyPromise._fulfill(); + this._finallyPromise = null; + } +}; + +PromiseSpawn.prototype._promiseCancelled = function() { + if (this._isResolved()) return; + var implementsReturn = typeof this._generator["return"] !== "undefined"; + + var result; + if (!implementsReturn) { + var reason = new Promise.CancellationError( + "generator .return() sentinel"); + Promise.coroutine.returnSentinel = reason; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + result = tryCatch(this._generator["throw"]).call(this._generator, + reason); + this._promise._popContext(); + } else { + this._promise._pushContext(); + result = tryCatch(this._generator["return"]).call(this._generator, + undefined); + this._promise._popContext(); + } + this._cancellationPhase = true; + this._yieldedPromise = null; + this._continue(result); +}; + +PromiseSpawn.prototype._promiseFulfilled = function(value) { + this._yieldedPromise = null; + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._promiseRejected = function(reason) { + this._yieldedPromise = null; + 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._resultCancelled = function() { + if (this._yieldedPromise instanceof Promise) { + var promise = this._yieldedPromise; + this._yieldedPromise = null; + promise.cancel(); + } +}; + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._promiseFulfilled(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + var promise = this._promise; + if (result === errorObj) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return promise._rejectCallback(result.e, false); + } + } + + var value = result.value; + if (result.done === true) { + this._cleanup(); + if (this._cancellationPhase) { + return promise.cancel(); + } else { + return 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._promiseRejected( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + this._yieldedPromise = maybePromise; + maybePromise._proxy(this, null); + } else if (((bitField & 33554432) !== 0)) { + Promise._async.invoke( + this._promiseFulfilled, this, maybePromise._value() + ); + } else if (((bitField & 16777216) !== 0)) { + Promise._async.invoke( + this._promiseRejected, this, maybePromise._reason() + ); + } else { + this._promiseCancelled(); + } + } +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\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); + var ret = spawn.promise(); + spawn._generator = generator; + spawn._promiseFulfilled(undefined); + return ret; + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + debug.deprecated("Promise.spawn()", "Promise.coroutine()"); + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/node_modules/bluebird/js/release/join.js b/node_modules/bluebird/js/release/join.js new file mode 100644 index 0000000..e7e19f0 --- /dev/null +++ b/node_modules/bluebird/js/release/join.js @@ -0,0 +1,165 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) { +var util = require("./util"); +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 promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise, async) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.asyncNeeded = true; \n\ + this.now = 0; \n\ + } \n\ + \n\ + [TheName].prototype._callFunction = function(promise) { \n\ + promise._pushContext(); \n\ + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + if (this.asyncNeeded) { \n\ + async.invoke(this._callFunction, this, promise); \n\ + } else { \n\ + this._callFunction(promise); \n\ + } \n\ + \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise, async); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", "async", code) + (tryCatch, errorObj, Promise, async); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + 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 <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + holder.asyncNeeded = false; + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + + if (!ret._isFateSealed()) { + if (holder.asyncNeeded) { + var context = Promise._getContext(); + holder.fn = util.contextBind(context, holder.fn); + } + ret._setAsyncGuaranteed(); + ret._setOnCancel(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/bluebird/js/release/map.js b/node_modules/bluebird/js/release/map.js new file mode 100644 index 0000000..91d5a82 --- /dev/null +++ b/node_modules/bluebird/js/release/map.js @@ -0,0 +1,175 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var context = Promise._getContext(); + this._callback = util.contextBind(context, fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = []; + async.invoke(this._asyncInit, this, undefined); + if (util.isArray(promises)) { + for (var i = 0; i < promises.length; ++i) { + var maybePromise = promises[i]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + } +} +util.inherits(MappingPromiseArray, PromiseArray); + +MappingPromiseArray.prototype._asyncInit = function() { + 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 (index < 0) { + index = (index * -1) - 1; + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return true; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return false; + } + if (preservedValues !== null) preservedValues[index] = value; + + var promise = this._promise; + var callback = this._callback; + var receiver = promise._boundValue(); + promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); + if (ret === errorObj) { + this._reject(ret.e); + return true; + } + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + if (limit >= 1) this._inFlight++; + values[index] = maybePromise; + maybePromise._proxy(this, (index + 1) * -1); + return false; + } else if (((bitField & 33554432) !== 0)) { + ret = maybePromise._value(); + } else if (((bitField & 16777216) !== 0)) { + this._reject(maybePromise._reason()); + return true; + } else { + this._cancel(); + return true; + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + return true; + } + return false; +}; + +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) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + + var limit = 0; + if (options !== undefined) { + if (typeof options === "object" && options !== null) { + if (typeof options.concurrency !== "number") { + return Promise.reject( + new TypeError("'concurrency' must be a number but it is " + + util.classString(options.concurrency))); + } + limit = options.concurrency; + } else { + return Promise.reject(new TypeError( + "options argument must be an object but it is " + + util.classString(options))); + } + } + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter).promise(); +} + +Promise.prototype.map = function (fn, options) { + return map(this, fn, options, null); +}; + +Promise.map = function (promises, fn, options, _filter) { + return map(promises, fn, options, _filter); +}; + + +}; diff --git a/node_modules/bluebird/js/release/method.js b/node_modules/bluebird/js/release/method.js new file mode 100644 index 0000000..ce9e4db --- /dev/null +++ b/node_modules/bluebird/js/release/method.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/node_modules/bluebird/js/release/nodeback.js b/node_modules/bluebird/js/release/nodeback.js new file mode 100644 index 0000000..71e69eb --- /dev/null +++ b/node_modules/bluebird/js/release/nodeback.js @@ -0,0 +1,51 @@ +"use strict"; +var util = require("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors"); +var OperationalError = errors.OperationalError; +var es5 = require("./es5"); + +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, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; diff --git a/node_modules/bluebird/js/release/nodeify.js b/node_modules/bluebird/js/release/nodeify.js new file mode 100644 index 0000000..ce2b190 --- /dev/null +++ b/node_modules/bluebird/js/release/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util"); +var async = Promise._async; +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 newReason = new Error(reason + ""); + 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/release/promise.js b/node_modules/bluebird/js/release/promise.js new file mode 100644 index 0000000..622a86f --- /dev/null +++ b/node_modules/bluebird/js/release/promise.js @@ -0,0 +1,819 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = require("./util"); +util.setReflectHandler(reflectHandler); + +var getDomain = function() { + var domain = process.domain; + if (domain === undefined) { + return null; + } + return domain; +}; +var getContextDefault = function() { + return null; +}; +var getContextDomain = function() { + return { + domain: getDomain(), + async: null + }; +}; +var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ? + require("async_hooks").AsyncResource : null; +var getContextAsyncHooks = function() { + return { + domain: getDomain(), + async: new AsyncResource("Bluebird::Promise") + }; +}; +var getContext = util.isNode ? getContextDomain : getContextDefault; +util.notEnumerableProp(Promise, "_getContext", getContext); +var enableAsyncHooks = function() { + getContext = getContextAsyncHooks; + util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks); +}; +var disableAsyncHooks = function() { + getContext = getContextDomain; + util.notEnumerableProp(Promise, "_getContext", getContextDomain); +}; + +var es5 = require("./es5"); +var Async = require("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = require("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = 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 = {}; +var tryConvertToPromise = require("./thenables")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = require("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; + +var debug = require("./debuggability")(Promise, Context, + enableAsyncHooks, disableAsyncHooks); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = require("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = require("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._resolveFromExecutor(executor); + this._promiseCreated(); + this._fireEvent("promiseCreated", this); +} + +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 (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("Catch statement predicate: " + + "expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + + if (typeof fn !== "function") { + throw new TypeError("The last argument to .catch() " + + "must be a function, got " + util.toString(fn)); + } + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && 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, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +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 () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.getNewLibraryCopy = module.exports; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + 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("expecting a function but got " + util.classString(fn)); + } + return async.setScheduler(fn); +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + this._fireEvent("promiseChained", this, promise); + } + + var context = getContext(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: util.contextBind(context, handler), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, + receiver, context); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; + this._fireEvent("promiseFulfilled", this); +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; + this._fireEvent("promiseRejected", this); +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; + this._fireEvent("promiseResolved", this); +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; + this._fireEvent("promiseCancelled", this); +}; + +Promise.prototype._setWillBeCancelled = function() { + this._bitField = this._bitField | 8388608; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + if (async.hasCustomScheduler()) return; + var bitField = this._bitField; + this._bitField = bitField | + (((bitField & 536870912) >> 2) ^ + 134217728); +}; + +Promise.prototype._setNoAsyncGuarantee = function() { + this._bitField = (this._bitField | 536870912) & + (~134217728); +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + context +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = util.contextBind(context, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + util.contextBind(context, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + util.contextBind(context, reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + + var promise = maybePromise._target(); + + if (promise === this) { + this._reject(makeSelfResolutionError()); + return; + } + + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(maybePromise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + if (executor === INTERNAL) return; + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj) { + promise._rejectCallback(x.e, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise, this); + 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._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (receiver instanceof PassThroughHandlerContext && + receiver.isFinallyHandler()) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + this._dereferenceTrace(); + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + async.settlePromises(this); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + es5.defineProperty(Promise.prototype, Symbol.toStringTag, { + get: function () { + return "Object"; + } + }); +} + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +require("./cancel")(Promise, PromiseArray, apiRejection, debug); +require("./direct_resolve")(Promise); +require("./synchronous_inspection")(Promise); +require("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async); +Promise.Promise = Promise; +Promise.version = "3.7.2"; +require('./call_get.js')(Promise); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./nodeify.js')(Promise); +require('./promisify.js')(Promise, INTERNAL); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./settle.js')(Promise, PromiseArray, debug); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./timers.js')(Promise, INTERNAL, debug); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +require('./any.js')(Promise); +require('./each.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._promise0 = value; + p._receiver0 = 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)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/node_modules/bluebird/js/release/promise_array.js b/node_modules/bluebird/js/release/promise_array.js new file mode 100644 index 0000000..8fc665a --- /dev/null +++ b/node_modules/bluebird/js/release/promise_array.js @@ -0,0 +1,186 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = require("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + values.suppressUnhandledRejections(); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +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(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise._isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/node_modules/bluebird/js/release/promisify.js b/node_modules/bluebird/js/release/promisify.js new file mode 100644 index 0000000..aa98e5b --- /dev/null +++ b/node_modules/bluebird/js/release/promisify.js @@ -0,0 +1,314 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util"); +var nodebackForPromise = require("./nodeback"); +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./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/MqrFmX\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 (!false) { +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, _, multiArgs) { + 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"; + var body = "'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, " + multiArgs + "); \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\ + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode); + body = body.replace("Parameters", parameterDeclaration(newParameterCount)); + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL", + body)( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { + 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, multiArgs); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { + 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, multiArgs); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, + fn, suffix, multiArgs); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver, multiArgs) { + return makeNodePromisified(callback, receiver, undefined, + callback, null, multiArgs); +} + +Promise.promisify = function (fn, options) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + if (isPromisified(fn)) { + return fn; + } + options = Object(options); + var receiver = options.context === undefined ? THIS : options.context; + var multiArgs = !!options.multiArgs; + var ret = promisify(fn, receiver, multiArgs); + 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/MqrFmX\u000a"); + } + options = Object(options); + var multiArgs = !!options.multiArgs; + 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/MqrFmX\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, + multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); + } + } + + return promisifyAll(target, suffix, filter, promisifier, multiArgs); +}; +}; + diff --git a/node_modules/bluebird/js/release/props.js b/node_modules/bluebird/js/release/props.js new file mode 100644 index 0000000..6a34aaf --- /dev/null +++ b/node_modules/bluebird/js/release/props.js @@ -0,0 +1,118 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util"); +var isObject = util.isObject; +var es5 = require("./es5"); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; + +var mapToEntries = (function() { + var index = 0; + var size = 0; + + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } + + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); + +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; + +function PropertiesPromiseArray(obj) { + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; + } + } + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, isMap ? -6 : -3); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () {}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val; + if (this._isMap) { + val = entriesToMap(this._values); + } else { + 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); + return true; + } + return false; +}; + +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/MqrFmX\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, 2); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/node_modules/bluebird/js/release/queue.js b/node_modules/bluebird/js/release/queue.js new file mode 100644 index 0000000..ffd36fd --- /dev/null +++ b/node_modules/bluebird/js/release/queue.js @@ -0,0 +1,73 @@ +"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.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/release/race.js b/node_modules/bluebird/js/release/race.js new file mode 100644 index 0000000..b862f46 --- /dev/null +++ b/node_modules/bluebird/js/release/race.js @@ -0,0 +1,49 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util"); + +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 { + promises = util.asArray(promises); + if (promises === null) + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 3); + } + 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/release/reduce.js b/node_modules/bluebird/js/release/reduce.js new file mode 100644 index 0000000..101ac22 --- /dev/null +++ b/node_modules/bluebird/js/release/reduce.js @@ -0,0 +1,183 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var context = Promise._getContext(); + this._fn = util.contextBind(context, fn); + if (initialValue !== undefined) { + initialValue = Promise.resolve(initialValue); + initialValue._attachCancellationCallback(this); + } + this._initialValue = initialValue; + this._currentCancellable = null; + if(_each === INTERNAL) { + this._eachValues = Array(this._length); + } else if (_each === 0) { + this._eachValues = null; + } else { + this._eachValues = undefined; + } + this._promise._captureStackTrace(); + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._gotAccum = function(accum) { + if (this._eachValues !== undefined && + this._eachValues !== null && + accum !== INTERNAL) { + this._eachValues.push(accum); + } +}; + +ReductionPromiseArray.prototype._eachComplete = function(value) { + if (this._eachValues !== null) { + this._eachValues.push(value); + } + return this._eachValues; +}; + +ReductionPromiseArray.prototype._init = function() {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function() { + this._resolve(this._eachValues !== undefined ? this._eachValues + : this._initialValue); +}; + +ReductionPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +ReductionPromiseArray.prototype._resolve = function(value) { + this._promise._resolveCallback(value); + this._values = null; +}; + +ReductionPromiseArray.prototype._resultCancelled = function(sender) { + if (sender === this._initialValue) return this._cancel(); + if (this._isResolved()) return; + this._resultCancelled$(); + if (this._currentCancellable instanceof Promise) { + this._currentCancellable.cancel(); + } + if (this._initialValue instanceof Promise) { + this._initialValue.cancel(); + } +}; + +ReductionPromiseArray.prototype._iterate = function (values) { + this._values = values; + var value; + var i; + var length = values.length; + if (this._initialValue !== undefined) { + value = this._initialValue; + i = 0; + } else { + value = Promise.resolve(values[0]); + i = 1; + } + + this._currentCancellable = value; + + for (var j = i; j < length; ++j) { + var maybePromise = values[j]; + if (maybePromise instanceof Promise) { + maybePromise.suppressUnhandledRejections(); + } + } + + if (!value.isRejected()) { + for (; i < length; ++i) { + var ctx = { + accum: null, + value: values[i], + index: i, + length: length, + array: this + }; + + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + + if ((i & 127) === 0) { + value._setNoAsyncGuarantee(); + } + } + } + + if (this._eachValues !== undefined) { + value = value + ._then(this._eachComplete, undefined, undefined, this, undefined); + } + value._then(completed, completed, undefined, value, this); +}; + +Promise.prototype.reduce = function (fn, initialValue) { + return reduce(this, fn, initialValue, null); +}; + +Promise.reduce = function (promises, fn, initialValue, _each) { + return reduce(promises, fn, initialValue, _each); +}; + +function completed(valueOrReason, array) { + if (this.isFulfilled()) { + array._resolve(valueOrReason); + } else { + array._reject(valueOrReason); + } +} + +function reduce(promises, fn, initialValue, _each) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var array = new ReductionPromiseArray(promises, fn, initialValue, _each); + return array.promise(); +} + +function gotAccum(accum) { + this.accum = accum; + this.array._gotAccum(accum); + var value = tryConvertToPromise(this.value, this.array._promise); + if (value instanceof Promise) { + this.array._currentCancellable = value; + return value._then(gotValue, undefined, undefined, this, undefined); + } else { + return gotValue.call(this, value); + } +} + +function gotValue(value) { + var array = this.array; + var promise = array._promise; + var fn = tryCatch(array._fn); + promise._pushContext(); + var ret; + if (array._eachValues !== undefined) { + ret = fn.call(promise._boundValue(), value, this.index, this.length); + } else { + ret = fn.call(promise._boundValue(), + this.accum, value, this.index, this.length); + } + if (ret instanceof Promise) { + array._currentCancellable = ret; + } + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", + promise + ); + return ret; +} +}; diff --git a/node_modules/bluebird/js/release/schedule.js b/node_modules/bluebird/js/release/schedule.js new file mode 100644 index 0000000..15197d1 --- /dev/null +++ b/node_modules/bluebird/js/release/schedule.js @@ -0,0 +1,62 @@ +"use strict"; +var util = require("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var NativePromise = util.getNativePromise(); +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if (typeof NativePromise === "function" && + typeof NativePromise.resolve === "function") { + var nativePromise = NativePromise.resolve(); + schedule = function(fn) { + nativePromise.then(fn); + }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + (window.navigator.standalone || window.cordova)) && + ("classList" in document.documentElement)) { + schedule = (function() { + var div = document.createElement("div"); + var opts = {attributes: true}; + var toggleScheduled = false; + var div2 = document.createElement("div"); + var o2 = new MutationObserver(function() { + div.classList.toggle("foo"); + toggleScheduled = false; + }); + o2.observe(div2, opts); + + var scheduleToggle = function() { + if (toggleScheduled) return; + toggleScheduled = true; + div2.classList.toggle("foo"); + }; + + return function schedule(fn) { + var o = new MutationObserver(function() { + o.disconnect(); + fn(); + }); + o.observe(div, opts); + scheduleToggle(); + }; + })(); +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; diff --git a/node_modules/bluebird/js/release/settle.js b/node_modules/bluebird/js/release/settle.js new file mode 100644 index 0000000..e24b204 --- /dev/null +++ b/node_modules/bluebird/js/release/settle.js @@ -0,0 +1,47 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray, debug) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 33554432; + ret._settledValueField = value; + return this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 16777216; + ret._settledValueField = reason; + return this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + debug.deprecated(".settle()", ".reflect()"); + return new SettledPromiseArray(promises).promise(); +}; + +Promise.allSettled = function (promises) { + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return Promise.settle(this); +}; +}; diff --git a/node_modules/bluebird/js/release/some.js b/node_modules/bluebird/js/release/some.js new file mode 100644 index 0000000..400d852 --- /dev/null +++ b/node_modules/bluebird/js/release/some.js @@ -0,0 +1,148 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util"); +var RangeError = require("./errors").RangeError; +var AggregateError = require("./errors").AggregateError; +var isArray = util.isArray; +var CANCELLATION = {}; + + +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); + } + return true; + } + return false; + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } + } + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; + } + return false; +}; + +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/MqrFmX\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/release/synchronous_inspection.js b/node_modules/bluebird/js/release/synchronous_inspection.js new file mode 100644 index 0000000..9c49d2e --- /dev/null +++ b/node_modules/bluebird/js/release/synchronous_inspection.js @@ -0,0 +1,103 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = 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/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = function() { + return (this._bitField & 8454144) !== 0; +}; + +Promise.prototype.__isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype._isCancelled = function() { + return this._target().__isCancelled(); +}; + +Promise.prototype.isCancelled = function() { + return (this._target()._bitField & 8454144) !== 0; +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/node_modules/bluebird/js/release/thenables.js b/node_modules/bluebird/js/release/thenables.js new file mode 100644 index 0000000..d6ab9aa --- /dev/null +++ b/node_modules/bluebird/js/release/thenables.js @@ -0,0 +1,86 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = 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") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + try { + return hasProp.call(obj, "_promise0"); + } catch (e) { + return false; + } +} + +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, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/node_modules/bluebird/js/release/timers.js b/node_modules/bluebird/js/release/timers.js new file mode 100644 index 0000000..cb8f1f4 --- /dev/null +++ b/node_modules/bluebird/js/release/timers.js @@ -0,0 +1,93 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, debug) { +var util = require("./util"); +var TimeoutError = Promise.TimeoutError; + +function HandleWrapper(handle) { + this.handle = handle; +} + +HandleWrapper.prototype._resultCancelled = function() { + clearTimeout(this.handle); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (ms, value) { + var ret; + var handle; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + if (debug.cancellation() && value instanceof Promise) { + ret._setOnCancel(value); + } + } else { + ret = new Promise(INTERNAL); + handle = setTimeout(function() { ret._fulfill(); }, +ms); + if (debug.cancellation()) { + ret._setOnCancel(new HandleWrapper(handle)); + } + ret._captureStackTrace(); + } + ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.prototype.delay = function (ms) { + return delay(ms, this); +}; + +var afterTimeout = function (promise, message, parent) { + var err; + if (typeof message !== "string") { + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._reject(err); + + if (parent != null) { + parent.cancel(); + } +}; + +function successClear(value) { + clearTimeout(this.handle); + return value; +} + +function failureClear(reason) { + clearTimeout(this.handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret, parent; + + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { + if (ret.isPending()) { + afterTimeout(ret, message, parent); + } + }, ms)); + + if (debug.cancellation()) { + parent = this.then(); + ret = parent._then(successClear, failureClear, + undefined, handleWrapper, undefined); + ret._setOnCancel(handleWrapper); + } else { + ret = this._then(successClear, failureClear, + undefined, handleWrapper, undefined); + } + + return ret; +}; + +}; diff --git a/node_modules/bluebird/js/release/using.js b/node_modules/bluebird/js/release/using.js new file mode 100644 index 0000000..65de531 --- /dev/null +++ b/node_modules/bluebird/js/release/using.js @@ -0,0 +1,226 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext, INTERNAL, debug) { + var util = require("./util"); + var TypeError = require("./errors").TypeError; + var inherits = require("./util").inherits; + var errorObj = util.errorObj; + var tryCatch = util.tryCatch; + var NULL = {}; + + 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 = new Promise(INTERNAL); + function iterator() { + if (i >= len) return ret._fulfill(); + 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; + } + + 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; + } + + function ResourceList(length) { + this.length = length; + this.promise = null; + this[length-1] = null; + } + + ResourceList.prototype._resultCancelled = function() { + var len = this.length; + for (var i = 0; i < len; ++i) { + var item = this[i]; + if (item instanceof Promise) { + item.cancel(); + } + } + }; + + 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("expecting a function but got " + util.classString(fn)); + } + 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 ResourceList(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 reflectedResources = new Array(resources.length); + for (var i = 0; i < reflectedResources.length; ++i) { + reflectedResources[i] = Promise.resolve(resources[i]).reflect(); + } + + var resultPromise = Promise.all(reflectedResources) + .then(function(inspections) { + for (var i = 0; i < inspections.length; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + errorObj.e = inspection.error(); + return errorObj; + } else if (!inspection.isFulfilled()) { + resultPromise.cancel(); + return; + } + inspections[i] = inspection.value(); + } + promise._pushContext(); + + fn = tryCatch(fn); + var ret = spreadArgs + ? fn.apply(undefined, inspections) : fn(inspections); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promiseCreated, "Promise.using", promise); + return ret; + }); + + var promise = resultPromise.lastly(function() { + var inspection = new Promise.PromiseInspection(resultPromise); + return dispose(resources, inspection); + }); + resources.promise = promise; + promise._setOnCancel(resources); + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 131072; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 131072) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~131072); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; diff --git a/node_modules/bluebird/js/release/util.js b/node_modules/bluebird/js/release/util.js new file mode 100644 index 0000000..8ca4d91 --- /dev/null +++ b/node_modules/bluebird/js/release/util.js @@ -0,0 +1,421 @@ +"use strict"; +var es5 = require("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +var globalObject = typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + this !== undefined ? this : null; + +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 typeof value === "function" || + typeof value === "object" && value !== null; +} + +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 FakeConstructor() {} + FakeConstructor.prototype = obj; + var receiver = new FakeConstructor(); + function ic() { + return typeof receiver.foo; + } + ic(); + ic(); + 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 isError(obj) { + return obj instanceof Error || + (obj !== null && + typeof obj === "object" && + typeof obj.message === "string" && + typeof obj.name === "string"); +} + +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 isError(obj) && 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 asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +function getNativePromise() { + if (typeof Promise === "function") { + try { + var promise = new Promise(function(){}); + if (classString(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +var reflectHandler; +function contextBind(ctx, cb) { + if (ctx === null || + typeof cb !== "function" || + cb === reflectHandler) { + return cb; + } + + if (ctx.domain !== null) { + cb = ctx.domain.bind(cb); + } + + var async = ctx.async; + if (async !== null) { + var old = cb; + cb = function() { + var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];}; + args[0] = old; + args[1] = this; + return async.runInAsyncScope.apply(async, args); + }; + } + return cb; +} + +var ret = { + setReflectHandler: function(fn) { + reflectHandler = fn; + }, + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + isError: isError, + 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, + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + contextBind: contextBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version; + if (process.versions && process.versions.node) { + version = process.versions.node.split(".").map(Number); + } else if (process.version) { + version = process.version.split(".").map(Number); + } + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); +ret.nodeSupportsAsyncResource = ret.isNode && (function() { + var supportsAsync = false; + try { + var res = require("async_hooks").AsyncResource; + supportsAsync = typeof res.prototype.runInAsyncScope === "function"; + } catch (e) { + supportsAsync = false; + } + return supportsAsync; +})(); + +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..3c05ba5 --- /dev/null +++ b/node_modules/bluebird/package.json @@ -0,0 +1,102 @@ +{ + "_from": "bluebird@^3.7.2", + "_id": "bluebird@3.7.2", + "_inBundle": false, + "_integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==", + "_location": "/bluebird", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bluebird@^3.7.2", + "name": "bluebird", + "escapedName": "bluebird", + "rawSpec": "^3.7.2", + "saveSpec": null, + "fetchSpec": "^3.7.2" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "_shasum": "9f229c15be272454ffa973ace0dbee79a1b0c36f", + "_spec": "bluebird@^3.7.2", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "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": "^6.0.2", + "acorn-walk": "^6.1.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/release", + "LICENSE" + ], + "homepage": "https://github.com/petkaantonov/bluebird", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "license": "MIT", + "main": "./js/release/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 --release --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", + "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", + "istanbul": "istanbul", + "lint": "node scripts/jshint.js", + "prepublish": "npm run generate-browser-core && npm run generate-browser-full", + "test": "node --expose-gc tools/test.js" + }, + "version": "3.7.2", + "webpack": "./js/release/bluebird.js" +} diff --git a/node_modules/buffer-more-ints/.travis.yml b/node_modules/buffer-more-ints/.travis.yml new file mode 100644 index 0000000..ed05f88 --- /dev/null +++ b/node_modules/buffer-more-ints/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" + - "0.6" diff --git a/node_modules/buffer-more-ints/LICENSE b/node_modules/buffer-more-ints/LICENSE new file mode 100644 index 0000000..e0d6370 --- /dev/null +++ b/node_modules/buffer-more-ints/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 David Wragg. 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/buffer-more-ints/README.md b/node_modules/buffer-more-ints/README.md new file mode 100644 index 0000000..771028f --- /dev/null +++ b/node_modules/buffer-more-ints/README.md @@ -0,0 +1,69 @@ +# buffer-more-ints: Add support for more integer widths to Buffer + +[![Build Status](https://travis-ci.org/dpw/node-buffer-more-ints.png)](https://travis-ci.org/dpw/node-buffer-more-ints) + +Node's Buffer only supports reading and writing integers of a limited +range of widths. This module provides support for more widths, so +that integers from 1 to 8 bytes (64 bits) can be accessed. The +support takes two forms. Firstly, as stand-alone functions similar to +the integer reading/writing methods of Buffer: + + $ node + > var moreints = require('buffer-more-ints') + undefined + > moreints.readInt64BE(new Buffer("0000deadbeef0000", "hex"), 0).toString(16) + 'deadbeef0000' + +Read and write functions for the regular widths (8, 16, 32) are also +present in this module, for consistency. + +The second form is methods patched into `Buffer.prototype`, installed +by requiring `'buffer-more-ints/polyfill'`: + + $ node + > require('buffer-more-ints/polyfill') + {} + > new Buffer("0000deadbeef0000", "hex").readInt64BE(0).toString(16) + 'deadbeef0000' + +buffer-more-ints/polyfill also adds methods `readIntBE`, `writeIntBE`, +and their LE and UInt counterparts, which take an initial argument +giving the width of the integer in bytes: + + > var b = new Buffer(3); + > b.writeIntLE(3, -123456, 0); + > b.toString('hex') + 'c01dfe' + > b.readIntLE(3, 0); + -123456 + +The functions added by buffer-more-ints are all implemented in terms +of the core Buffer functions. Part way through writing the code, I +discovered that node.js currently implements those in JavaScript, so +this doesn't lead to performance benefits. But should node ever +switch to implementing its Buffer operations natively, this +module should get a speed boost. + +## Limitations + +As JavaScript uses IEEE754 doubles for numbers, the contiguous range +of integers it can represent is [-2^53 - 1, 2^53 - 1]. So only +integer widths up to 6 bytes or 48 bits can be read exactly. Reads of +7 or 8 bytes (56 or 64 bits) will return the closest value that can be +represented as a JavaScript number. + +In certain situations it might be important to check that a JavaScript +number was read exactly. The `isContiguousInt` or +`Buffer.isContiguousInt` (polyfill) function will determine this: + + > Buffer.isContiguousInt(0x1fffffffffffff); + true + > Buffer.isContiguousInt(0x20000000000000); + false + +And `assertContiguousInt` asserts that a number is so: + + > Buffer.assertContiguousInt(0x1fffffffffffff); + undefined + > Buffer.assertContiguousInt(0x20000000000000); + AssertionError: number cannot be represented as a contiguous integer diff --git a/node_modules/buffer-more-ints/buffer-more-ints-tests.js b/node_modules/buffer-more-ints/buffer-more-ints-tests.js new file mode 100644 index 0000000..dbcd118 --- /dev/null +++ b/node_modules/buffer-more-ints/buffer-more-ints-tests.js @@ -0,0 +1,183 @@ +'use strict'; + +require('./polyfill'); + +// A simple abbreviation to obtain a buffer from a hex string +function h2b(str) { + return new Buffer(str, "hex"); +} + +// Reverse a buffer +function reverse(buf) { + var res = new Buffer(buf.length); + for (var i = 0, j = buf.length - 1; j >= 0; i++, j--) { + res[i] = buf[j]; + } + return res; +} + +// Fill a buffer with distinctive data +function scrub(buf) { + var pos = 0; + var written; + while ((written = buf.write("deadbeef", pos, 4, "hex")) == 4) { + pos += written; + } + return buf; +} + +function xint_case(xint) { + return function (assert, hex, val, inexact) { + var readBE = "read" + xint + "BE"; + var writeBE = "write" + xint + "BE"; + var readLE = "read" + xint + "LE"; + var writeLE = "write" + xint + "LE"; + + var len = hex.length / 2; + + // Straightforward read cases + assert.equal(h2b(hex)[readBE](len, 0), val); + assert.equal(reverse(h2b(hex))[readLE](len, 0), val); + + // Test straightforward writes and noAssert writes off the ends of + // the buffer + var buf = scrub(new Buffer(len)); + buf[writeBE](len, val, 0); + if (!inexact) { + assert.equal(buf.toString("hex"), hex); + } else { + assert.equal(buf[readBE](len, 0), val); + } + + scrub(buf); + buf[writeLE](len, val, 0); + if (!inexact) { + assert.equal(reverse(buf).toString("hex"), hex); + } else { + assert.equal(buf[readLE](len, 0), val); + } + + // Accesses off the ends of the buffer should throw. + assert.throws(function () { h2b(hex)[readBE](len, -1); }); + assert.throws(function () { h2b(hex)[readBE](len, 1); }); + assert.throws(function () { reverse(h2b(hex))[readLE](len, 1); }); + assert.throws(function () { reverse(h2b(hex))[readLE](len, -1); }); + assert.throws(function () { buf[writeBE](len, val, 1); }); + assert.throws(function () { buf[writeBE](len, val, -1); }); + assert.throws(function () { buf[writeLE](len, val, 1); }); + assert.throws(function () { buf[writeLE](len, val, -1); }); + }; +} + +var uint_case = xint_case("UInt"); +var int_case = xint_case("Int"); + +module.exports.uint = function (assert) { + uint_case(assert, "00", 0x00); + uint_case(assert, "01", 0x01); + uint_case(assert, "ff", 0xff); + + uint_case(assert, "0000", 0x0000); + uint_case(assert, "0102", 0x0102); + uint_case(assert, "ffff", 0xffff); + + uint_case(assert, "000000", 0x000000); + uint_case(assert, "010203", 0x010203); + uint_case(assert, "ffffff", 0xffffff); + + uint_case(assert, "00000000", 0x00000000); + uint_case(assert, "01020304", 0x01020304); + uint_case(assert, "ffffffff", 0xffffffff); + + uint_case(assert, "0000000000", 0x0000000000); + uint_case(assert, "0102030405", 0x0102030405); + uint_case(assert, "ffffffffff", 0xffffffffff); + + uint_case(assert, "000000000000", 0x000000000000); + uint_case(assert, "010203040506", 0x010203040506); + uint_case(assert, "ffffffffffff", 0xffffffffffff); + + uint_case(assert, "00000000000000", 0x00000000000000); + uint_case(assert, "01020304050607", 0x01020304050607); + uint_case(assert, "ffffffffffffff", 0xffffffffffffff); + + uint_case(assert, "0000000000000000", 0x0000000000000000); + uint_case(assert, "0102030405060708", 0x0102030405060708, true); + uint_case(assert, "ffffffffffffffff", 0xffffffffffffffff); + + assert.done(); +}; + +module.exports.int = function (assert) { + int_case(assert, "00", 0x00); + int_case(assert, "01", 0x01); + int_case(assert, "7f", 0x7f); + int_case(assert, "80", -0x80); + int_case(assert, "ff", -0x01); + + int_case(assert, "0000", 0x0000); + int_case(assert, "0102", 0x0102); + int_case(assert, "7fff", 0x7fff); + int_case(assert, "8000", -0x8000); + int_case(assert, "ffff", -0x0001); + + int_case(assert, "000000", 0x000000); + int_case(assert, "010203", 0x010203); + int_case(assert, "7fffff", 0x7fffff); + int_case(assert, "800000", -0x800000); + int_case(assert, "ffffff", -0x000001); + + int_case(assert, "00000000", 0x00000000); + int_case(assert, "01020304", 0x01020304); + int_case(assert, "7fffffff", 0x7fffffff); + int_case(assert, "80000000", -0x80000000); + int_case(assert, "ffffffff", -0x00000001); + + int_case(assert, "0000000000", 0x0000000000); + int_case(assert, "0102030405", 0x0102030405); + int_case(assert, "7fffffffff", 0x7fffffffff); + int_case(assert, "8000000000", -0x8000000000); + int_case(assert, "ffffffffff", -0x0000000001); + + int_case(assert, "000000000000", 0x000000000000); + int_case(assert, "010203040506", 0x010203040506); + int_case(assert, "7fffffffffff", 0x7fffffffffff); + int_case(assert, "800000000000", -0x800000000000); + int_case(assert, "ffffffffffff", -0x000000000001); + + int_case(assert, "00000000000000", 0x00000000000000); + int_case(assert, "01020304050607", 0x01020304050607); + int_case(assert, "7fffffffffffff", 0x7fffffffffffff); + int_case(assert, "80000000000000", -0x80000000000000); + int_case(assert, "ffffffffffffff", -0x00000000000001); + + int_case(assert, "0000000000000000", 0x0000000000000000); + int_case(assert, "0102030405060708", 0x0102030405060708, true); + int_case(assert, "7fffffffffffffff", 0x7fffffffffffffff); + int_case(assert, "8000000000000000", -0x8000000000000000); + int_case(assert, "ffffffffffffffff", -0x0000000000000001); + + assert.done(); +}; + +module.exports.isContiguousInt = function (assert) { + assert.equal(Buffer.isContiguousInt(0x1fffffffffffff), true); + assert.equal(Buffer.isContiguousInt(0x20000000000000), false); + assert.equal(Buffer.isContiguousInt(-0x1fffffffffffff), true); + assert.equal(Buffer.isContiguousInt(-0x20000000000000), false); + + assert.doesNotThrow(function () { + Buffer.assertContiguousInt(0x1fffffffffffff); + }); + assert.throws(function () { + Buffer.assertContiguousInt(0x20000000000000); + }); + assert.doesNotThrow(function () { + Buffer.assertContiguousInt(-0x1fffffffffffff); + }); + assert.throws(function () { + Buffer.assertContiguousInt(-0x20000000000000); + }); + + assert.done(); +}; diff --git a/node_modules/buffer-more-ints/buffer-more-ints.js b/node_modules/buffer-more-ints/buffer-more-ints.js new file mode 100644 index 0000000..a35ae03 --- /dev/null +++ b/node_modules/buffer-more-ints/buffer-more-ints.js @@ -0,0 +1,432 @@ +'use strict'; + +// JavaScript is numerically challenged +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16); +var SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// The maximum contiguous integer that can be held in a IEEE754 double +var MAX_INT = 0x1fffffffffffff; + +function isContiguousInt(val) { + return val <= MAX_INT && val >= -MAX_INT; +} + +function assertContiguousInt(val) { + if (!isContiguousInt(val)) { + throw new TypeError("number cannot be represented as a contiguous integer"); + } +} + +module.exports.isContiguousInt = isContiguousInt; +module.exports.assertContiguousInt = assertContiguousInt; + +// Fill in the regular procedures +['UInt', 'Int'].forEach(function (sign) { + var suffix = sign + '8'; + module.exports['read' + suffix] = + Buffer.prototype['read' + suffix].call; + module.exports['write' + suffix] = + Buffer.prototype['write' + suffix].call; + + ['16', '32'].forEach(function (size) { + ['LE', 'BE'].forEach(function (endian) { + var suffix = sign + size + endian; + var read = Buffer.prototype['read' + suffix]; + module.exports['read' + suffix] = + function (buf, offset) { + return read.call(buf, offset); + }; + var write = Buffer.prototype['write' + suffix]; + module.exports['write' + suffix] = + function (buf, val, offset) { + return write.call(buf, val, offset); + }; + }); + }); +}); + +// Check that a value is an integer within the given range +function check_value(val, min, max) { + val = +val; + if (typeof(val) != 'number' || val < min || val > max || Math.floor(val) !== val) { + throw new TypeError("\"value\" argument is out of bounds"); + } + return val; +} + +// Check that something is within the Buffer bounds +function check_bounds(buf, offset, len) { + if (offset < 0 || offset + len > buf.length) { + throw new RangeError("Index out of range"); + } +} + +function readUInt24BE(buf, offset) { + return buf.readUInt8(offset) << 16 | buf.readUInt16BE(offset + 1); +} +module.exports.readUInt24BE = readUInt24BE; + +function writeUInt24BE(buf, val, offset) { + val = check_value(val, 0, 0xffffff); + check_bounds(buf, offset, 3); + buf.writeUInt8(val >>> 16, offset); + buf.writeUInt16BE(val & 0xffff, offset + 1); +} +module.exports.writeUInt24BE = writeUInt24BE; + +function readUInt40BE(buf, offset) { + return (buf.readUInt8(offset) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1); +} +module.exports.readUInt40BE = readUInt40BE; + +function writeUInt40BE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffff); + check_bounds(buf, offset, 5); + buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 1); +} +module.exports.writeUInt40BE = writeUInt40BE; + +function readUInt48BE(buf, offset) { + return buf.readUInt16BE(offset) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2); +} +module.exports.readUInt48BE = readUInt48BE; + +function writeUInt48BE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffff); + check_bounds(buf, offset, 6); + buf.writeUInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 2); +} +module.exports.writeUInt48BE = writeUInt48BE; + +function readUInt56BE(buf, offset) { + return ((buf.readUInt8(offset) || 0) << 16 | buf.readUInt16BE(offset + 1)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3); +} +module.exports.readUInt56BE = readUInt56BE; + +function writeUInt56BE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffffff); + check_bounds(buf, offset, 7); + + if (val < 0x100000000000000) { + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt8(hi >>> 16, offset); + buf.writeUInt16BE(hi & 0xffff, offset + 1); + buf.writeInt32BE(val & -1, offset + 3); + } else { + // Special case because 2^56-1 gets rounded up to 2^56 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeUInt56BE = writeUInt56BE; + +function readUInt64BE(buf, offset) { + return buf.readUInt32BE(offset) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4); +} +module.exports.readUInt64BE = readUInt64BE; + +function writeUInt64BE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffffffff); + check_bounds(buf, offset, 8); + + if (val < 0x10000000000000000) { + buf.writeUInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 4); + } else { + // Special case because 2^64-1 gets rounded up to 2^64 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeUInt64BE = writeUInt64BE; + +function readUInt24LE(buf, offset) { + return buf.readUInt8(offset + 2) << 16 | buf.readUInt16LE(offset); +} +module.exports.readUInt24LE = readUInt24LE; + +function writeUInt24LE(buf, val, offset) { + val = check_value(val, 0, 0xffffff); + check_bounds(buf, offset, 3); + + buf.writeUInt16LE(val & 0xffff, offset); + buf.writeUInt8(val >>> 16, offset + 2); +} +module.exports.writeUInt24LE = writeUInt24LE; + +function readUInt40LE(buf, offset) { + return (buf.readUInt8(offset + 4) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readUInt40LE = readUInt40LE; + +function writeUInt40LE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffff); + check_bounds(buf, offset, 5); + buf.writeInt32LE(val & -1, offset); + buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4); +} +module.exports.writeUInt40LE = writeUInt40LE; + +function readUInt48LE(buf, offset) { + return buf.readUInt16LE(offset + 4) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readUInt48LE = readUInt48LE; + +function writeUInt48LE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffff); + check_bounds(buf, offset, 6); + buf.writeInt32LE(val & -1, offset); + buf.writeUInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4); +} +module.exports.writeUInt48LE = writeUInt48LE; + +function readUInt56LE(buf, offset) { + return ((buf.readUInt8(offset + 6) || 0) << 16 | buf.readUInt16LE(offset + 4)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readUInt56LE = readUInt56LE; + +function writeUInt56LE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffffff); + check_bounds(buf, offset, 7); + + if (val < 0x100000000000000) { + buf.writeInt32LE(val & -1, offset); + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt16LE(hi & 0xffff, offset + 4); + buf.writeUInt8(hi >>> 16, offset + 6); + } else { + // Special case because 2^56-1 gets rounded up to 2^56 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeUInt56LE = writeUInt56LE; + +function readUInt64LE(buf, offset) { + return buf.readUInt32LE(offset + 4) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readUInt64LE = readUInt64LE; + +function writeUInt64LE(buf, val, offset) { + val = check_value(val, 0, 0xffffffffffffffff); + check_bounds(buf, offset, 8); + + if (val < 0x10000000000000000) { + buf.writeInt32LE(val & -1, offset); + buf.writeUInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4); + } else { + // Special case because 2^64-1 gets rounded up to 2^64 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeUInt64LE = writeUInt64LE; + + +function readInt24BE(buf, offset) { + return (buf.readInt8(offset) << 16) + buf.readUInt16BE(offset + 1); +} +module.exports.readInt24BE = readInt24BE; + +function writeInt24BE(buf, val, offset) { + val = check_value(val, -0x800000, 0x7fffff); + check_bounds(buf, offset, 3); + buf.writeInt8(val >> 16, offset); + buf.writeUInt16BE(val & 0xffff, offset + 1); +} +module.exports.writeInt24BE = writeInt24BE; + +function readInt40BE(buf, offset) { + return (buf.readInt8(offset) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1); +} +module.exports.readInt40BE = readInt40BE; + +function writeInt40BE(buf, val, offset) { + val = check_value(val, -0x8000000000, 0x7fffffffff); + check_bounds(buf, offset, 5); + buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 1); +} +module.exports.writeInt40BE = writeInt40BE; + +function readInt48BE(buf, offset) { + return buf.readInt16BE(offset) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2); +} +module.exports.readInt48BE = readInt48BE; + +function writeInt48BE(buf, val, offset) { + val = check_value(val, -0x800000000000, 0x7fffffffffff); + check_bounds(buf, offset, 6); + buf.writeInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 2); +} +module.exports.writeInt48BE = writeInt48BE; + +function readInt56BE(buf, offset) { + return (((buf.readInt8(offset) || 0) << 16) + buf.readUInt16BE(offset + 1)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3); +} +module.exports.readInt56BE = readInt56BE; + +function writeInt56BE(buf, val, offset) { + val = check_value(val, -0x800000000000000, 0x7fffffffffffff); + check_bounds(buf, offset, 7); + + if (val < 0x80000000000000) { + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeInt8(hi >> 16, offset); + buf.writeUInt16BE(hi & 0xffff, offset + 1); + buf.writeInt32BE(val & -1, offset + 3); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0x7f; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeInt56BE = writeInt56BE; + +function readInt64BE(buf, offset) { + return buf.readInt32BE(offset) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4); +} +module.exports.readInt64BE = readInt64BE; + +function writeInt64BE(buf, val, offset) { + val = check_value(val, -0x800000000000000000, 0x7fffffffffffffff); + check_bounds(buf, offset, 8); + + if (val < 0x8000000000000000) { + buf.writeInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset); + buf.writeInt32BE(val & -1, offset + 4); + } else { + // Special case because 2^63-1 gets rounded up to 2^63 + buf[offset] = 0x7f; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeInt64BE = writeInt64BE; + +function readInt24LE(buf, offset) { + return (buf.readInt8(offset + 2) << 16) + buf.readUInt16LE(offset); +} +module.exports.readInt24LE = readInt24LE; + +function writeInt24LE(buf, val, offset) { + val = check_value(val, -0x800000, 0x7fffff); + check_bounds(buf, offset, 3); + buf.writeUInt16LE(val & 0xffff, offset); + buf.writeInt8(val >> 16, offset + 2); +} +module.exports.writeInt24LE = writeInt24LE; + +function readInt40LE(buf, offset) { + return (buf.readInt8(offset + 4) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readInt40LE = readInt40LE; + +function writeInt40LE(buf, val, offset) { + val = check_value(val, -0x8000000000, 0x7fffffffff); + check_bounds(buf, offset, 5); + buf.writeInt32LE(val & -1, offset); + buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4); +} +module.exports.writeInt40LE = writeInt40LE; + +function readInt48LE(buf, offset) { + return buf.readInt16LE(offset + 4) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readInt48LE = readInt48LE; + +function writeInt48LE(buf, val, offset) { + val = check_value(val, -0x800000000000, 0x7fffffffffff); + check_bounds(buf, offset, 6); + buf.writeInt32LE(val & -1, offset); + buf.writeInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4); +} +module.exports.writeInt48LE = writeInt48LE; + +function readInt56LE(buf, offset) { + return (((buf.readInt8(offset + 6) || 0) << 16) + buf.readUInt16LE(offset + 4)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readInt56LE = readInt56LE; + +function writeInt56LE(buf, val, offset) { + val = check_value(val, -0x80000000000000, 0x7fffffffffffff); + check_bounds(buf, offset, 7); + + if (val < 0x80000000000000) { + buf.writeInt32LE(val & -1, offset); + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt16LE(hi & 0xffff, offset + 4); + buf.writeInt8(hi >> 16, offset + 6); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0x7f; + } +} +module.exports.writeInt56LE = writeInt56LE; + +function readInt64LE(buf, offset) { + return buf.readInt32LE(offset + 4) * SHIFT_LEFT_32 + buf.readUInt32LE(offset); +} +module.exports.readInt64LE = readInt64LE; + +function writeInt64LE(buf, val, offset) { + val = check_value(val, -0x8000000000000000, 0x7fffffffffffffff); + check_bounds(buf, offset, 8); + + if (val < 0x8000000000000000) { + buf.writeInt32LE(val & -1, offset); + buf.writeInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0x7f; + } +} +module.exports.writeInt64LE = writeInt64LE; diff --git a/node_modules/buffer-more-ints/package.json b/node_modules/buffer-more-ints/package.json new file mode 100644 index 0000000..1f6b16c --- /dev/null +++ b/node_modules/buffer-more-ints/package.json @@ -0,0 +1,51 @@ +{ + "_from": "buffer-more-ints@~1.0.0", + "_id": "buffer-more-ints@1.0.0", + "_inBundle": false, + "_integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==", + "_location": "/buffer-more-ints", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "buffer-more-ints@~1.0.0", + "name": "buffer-more-ints", + "escapedName": "buffer-more-ints", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/amqplib", + "/bitsyntax" + ], + "_resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "_shasum": "ef4f8e2dddbad429ed3828a9c55d44f05c611422", + "_spec": "buffer-more-ints@~1.0.0", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "author": { + "name": "David Wragg", + "email": "david@wragg.org" + }, + "bugs": { + "url": "https://github.com/dpw/node-buffer-more-ints/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Add support for more integer widths to Buffer", + "devDependencies": { + "nodeunit": "" + }, + "homepage": "https://github.com/dpw/node-buffer-more-ints", + "license": "MIT", + "main": "buffer-more-ints.js", + "name": "buffer-more-ints", + "repository": { + "type": "git", + "url": "git+https://github.com/dpw/node-buffer-more-ints.git" + }, + "scripts": { + "test": "node ./node_modules/nodeunit/bin/nodeunit buffer-more-ints-tests.js" + }, + "version": "1.0.0" +} diff --git a/node_modules/buffer-more-ints/polyfill.js b/node_modules/buffer-more-ints/polyfill.js new file mode 100644 index 0000000..757d68b --- /dev/null +++ b/node_modules/buffer-more-ints/polyfill.js @@ -0,0 +1,71 @@ +'use strict'; + +var bmi = require('./buffer-more-ints'); + +Buffer.isContiguousInt = bmi.isContiguousInt; +Buffer.assertContiguousInt = bmi.assertContiguousInt; + +['UInt', 'Int'].forEach(function (signed) { + ['24', '40', '48', '56', '64'].forEach(function (size) { + ['BE', 'LE'].forEach(function (endian) { + var read = 'read' + signed + size + endian; + var reader = bmi[read]; + Buffer.prototype[read] = function(offset) { + return reader(this, offset); + }; + var write = 'write' + signed + size + endian; + var writer = bmi[write]; + Buffer.prototype[write] = function(val, offset) { + writer(this, val, offset); + }; + }); + }); +}); + +// Buffer.prototype.read{UInt,Int}8 returns undefined if the offset is +// outside of the buffer, unlike for other widths. These functions +// make it consistent with the others. +var consistent_readX8 = { + readUInt8: function (offset) { + return this.readUInt8(offset) || 0; + }, + readInt8: function (offset) { + return this.readInt8(offset) || 0; + } +}; + +function make_accessor(read, prefix, suffix) { + var accessors = [false, + (read ? consistent_readX8 : Buffer.prototype)[prefix + 8]]; + + for (var i = 16; i <= 64; i += 8) { + accessors.push(Buffer.prototype[prefix + i + suffix]); + } + + if (read) { + Buffer.prototype[prefix + suffix] = function (len, offset) { + var reader = accessors[len]; + if (reader) { + return reader.call(this, offset); + } else { + throw new Error("Cannot read integer of length " + len); + } + }; + } else { + Buffer.prototype[prefix + suffix] = function (len, val, offset) { + var writer = accessors[len]; + if (writer) { + return writer.call(this, val, offset); + } else { + throw new Error("Cannot write integer of length " + len); + } + } + } +} + +['UInt', 'Int'].forEach(function (t) { + ['BE', 'LE'].forEach(function (e) { + make_accessor(true, "read" + t, e); + make_accessor(false, "write" + t, e); + }); +}); diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +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. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..6e5a20d --- /dev/null +++ b/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// 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(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +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 objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (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 = require('buffer').Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json new file mode 100644 index 0000000..b8d5595 --- /dev/null +++ b/node_modules/core-util-is/package.json @@ -0,0 +1,68 @@ +{ + "_from": "core-util-is@~1.0.0", + "_id": "core-util-is@1.0.3", + "_inBundle": false, + "_integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "_location": "/core-util-is", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "core-util-is@~1.0.0", + "name": "core-util-is", + "escapedName": "core-util-is", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "_shasum": "a6042d3634c2b27e9328f837b965fac83808db85", + "_spec": "core-util-is@~1.0.0", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\readable-stream", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The `util.is*` functions introduced in Node v0.12.", + "devDependencies": { + "tap": "^15.0.9" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/isaacs/core-util-is#readme", + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "license": "MIT", + "main": "lib/util.js", + "name": "core-util-is", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "scripts": { + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preversion": "npm test", + "test": "tap test.js" + }, + "version": "1.0.3" +} diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/debug/.travis.yml b/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +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/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +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/Makefile b/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# 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 + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +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) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env: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 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:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```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, 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) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +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'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 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/debug/component.json b/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/debug/karma.conf.js b/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..52cf62b --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,88 @@ +{ + "_from": "debug@~2.6.9", + "_id": "debug@2.6.9", + "_inBundle": false, + "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "debug@~2.6.9", + "name": "debug", + "escapedName": "debug", + "rawSpec": "~2.6.9", + "saveSpec": null, + "fetchSpec": "~2.6.9" + }, + "_requiredBy": [ + "/bitsyntax" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", + "_spec": "debug@~2.6.9", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\bitsyntax", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/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" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "2.0.0" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "2.6.9" +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * 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() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // 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-zA-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); +} + +/** + * 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) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + 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/src/debug.js b/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +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, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-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; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * 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); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? 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/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/inspector-log.js b/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * 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.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * 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; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, 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; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (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) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..115e1af --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@~2.0.1", + "_id": "inherits@2.0.4", + "_inBundle": false, + "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@~2.0.1", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "~2.0.1", + "saveSpec": null, + "fetchSpec": "~2.0.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", + "_spec": "inherits@~2.0.1", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\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": "^14.2.4" + }, + "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": "tap" + }, + "version": "2.0.4" +} diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# 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/isarray/build/build.js b/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * 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/isarray/component.json b/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "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/isarray/index.js b/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json new file mode 100644 index 0000000..009253a --- /dev/null +++ b/node_modules/isarray/package.json @@ -0,0 +1,57 @@ +{ + "_from": "isarray@0.0.1", + "_id": "isarray@0.0.1", + "_inBundle": false, + "_integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "_location": "/isarray", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "isarray@0.0.1", + "name": "isarray", + "escapedName": "isarray", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_spec": "isarray@0.0.1", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\readable-stream", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Array#isArray for older browsers", + "devDependencies": { + "tap": "*" + }, + "homepage": "https://github.com/juliangruber/isarray", + "keywords": [ + "browser", + "isarray", + "array" + ], + "license": "MIT", + "main": "index.js", + "name": "isarray", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "0.0.1" +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..6a522b1 --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * 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] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + 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; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(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 fmtLong(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/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..69b6125 --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +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/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..3d071a2 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,69 @@ +{ + "_from": "ms@2.0.0", + "_id": "ms@2.0.0", + "_inBundle": false, + "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.0.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", + "_spec": "ms@2.0.0", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\debug", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Tiny milisecond conversion utility", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.0.0" +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..84a9974 --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```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('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- 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. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/querystringify/LICENSE b/node_modules/querystringify/LICENSE new file mode 100644 index 0000000..6dc9316 --- /dev/null +++ b/node_modules/querystringify/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the 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/querystringify/README.md b/node_modules/querystringify/README.md new file mode 100644 index 0000000..0339638 --- /dev/null +++ b/node_modules/querystringify/README.md @@ -0,0 +1,61 @@ +# querystringify + +[![Version npm](http://img.shields.io/npm/v/querystringify.svg?style=flat-square)](https://www.npmjs.com/package/querystringify)[![Build Status](http://img.shields.io/travis/unshiftio/querystringify/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/querystringify)[![Dependencies](https://img.shields.io/david/unshiftio/querystringify.svg?style=flat-square)](https://david-dm.org/unshiftio/querystringify)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/querystringify/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/querystringify?branch=master) + +A somewhat JSON compatible interface for query string parsing. This query string +parser is dumb, don't expect to much from it as it only wants to parse simple +query strings. If you want to parse complex, multi level and deeply nested +query strings then you should ask your self. WTF am I doing? + +## Installation + +This module is released in npm as `querystringify`. It's also compatible with +`browserify` so it can be used on the server as well as on the client. To +install it simply run the following command from your CLI: + +``` +npm install --save querystringify +``` + +## Usage + +In the following examples we assume that you've already required the library as: + +```js +'use strict'; + +var qs = require('querystringify'); +``` + +### qs.parse() + +The parse method transforms a given query string in to an object. Parameters +without values are set to empty strings. It does not care if your query string +is prefixed with a `?`, a `#`, or not prefixed. It just extracts the parts +between the `=` and `&`: + +```js +qs.parse('?foo=bar'); // { foo: 'bar' } +qs.parse('#foo=bar'); // { foo: 'bar' } +qs.parse('foo=bar'); // { foo: 'bar' } +qs.parse('foo=bar&bar=foo'); // { foo: 'bar', bar: 'foo' } +qs.parse('foo&bar=foo'); // { foo: '', bar: 'foo' } +``` + +### qs.stringify() + +This transforms a given object in to a query string. By default we return the +query string without a `?` prefix. If you want to prefix it by default simply +supply `true` as second argument. If it should be prefixed by something else +simply supply a string with the prefix value as second argument: + +```js +qs.stringify({ foo: bar }); // foo=bar +qs.stringify({ foo: bar }, true); // ?foo=bar +qs.stringify({ foo: bar }, '#'); // #foo=bar +qs.stringify({ foo: '' }, '&'); // &foo= +``` + +## License + +MIT diff --git a/node_modules/querystringify/index.js b/node_modules/querystringify/index.js new file mode 100644 index 0000000..58c9808 --- /dev/null +++ b/node_modules/querystringify/index.js @@ -0,0 +1,118 @@ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , undef; + +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String|Null} The decoded string. + * @api private + */ +function decode(input) { + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} + +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } +} + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?#&]+)=?([^&]*)/g + , result = {} + , part; + + while (part = parser.exec(query)) { + var key = decode(part[1]) + , value = decode(part[2]); + + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; + result[key] = value; + } + + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + + var pairs = [] + , value + , key; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + + for (key in obj) { + if (has.call(obj, key)) { + value = obj[key]; + + // + // Edge cases where we actually want to encode the value to an empty + // string instead of the stringified value. + // + if (!value && (value === null || value === undef || isNaN(value))) { + value = ''; + } + + key = encode(key); + value = encode(value); + + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key +'='+ value); + } + } + + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; diff --git a/node_modules/querystringify/package.json b/node_modules/querystringify/package.json new file mode 100644 index 0000000..fc9ddaf --- /dev/null +++ b/node_modules/querystringify/package.json @@ -0,0 +1,65 @@ +{ + "_from": "querystringify@^2.1.1", + "_id": "querystringify@2.2.0", + "_inBundle": false, + "_integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "_location": "/querystringify", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "querystringify@^2.1.1", + "name": "querystringify", + "escapedName": "querystringify", + "rawSpec": "^2.1.1", + "saveSpec": null, + "fetchSpec": "^2.1.1" + }, + "_requiredBy": [ + "/url-parse" + ], + "_resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "_shasum": "3345941b4153cb9d082d8eee4cda2016a9aef7f6", + "_spec": "querystringify@^2.1.1", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\url-parse", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/unshiftio/querystringify/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Querystringify - Small, simple but powerful query string parser.", + "devDependencies": { + "assume": "^2.1.0", + "coveralls": "^3.1.0", + "mocha": "^8.1.1", + "nyc": "^15.1.0", + "pre-commit": "^1.2.2" + }, + "homepage": "https://github.com/unshiftio/querystringify", + "keywords": [ + "query", + "string", + "query-string", + "querystring", + "qs", + "stringify", + "parse", + "decode", + "encode" + ], + "license": "MIT", + "main": "index.js", + "name": "querystringify", + "repository": { + "type": "git", + "url": "git+https://github.com/unshiftio/querystringify.git" + }, + "scripts": { + "test": "nyc --reporter=html --reporter=text mocha test.js", + "watch": "mocha --watch test.js" + }, + "version": "2.2.0" +} diff --git a/node_modules/readable-stream/.npmignore b/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +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..e46b823 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# 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/readable-stream/duplex.js b/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/readable-stream/float.patch b/node_modules/readable-stream/float.patch new file mode 100644 index 0000000..b984607 --- /dev/null +++ b/node_modules/readable-stream/float.patch @@ -0,0 +1,923 @@ +diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js +index c5a741c..a2e0d8e 100644 +--- a/lib/_stream_duplex.js ++++ b/lib/_stream_duplex.js +@@ -26,8 +26,8 @@ + + module.exports = Duplex; + var util = require('util'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('./_stream_readable'); ++var Writable = require('./_stream_writable'); + + util.inherits(Duplex, Readable); + +diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js +index a5e9864..330c247 100644 +--- a/lib/_stream_passthrough.js ++++ b/lib/_stream_passthrough.js +@@ -25,7 +25,7 @@ + + module.exports = PassThrough; + +-var Transform = require('_stream_transform'); ++var Transform = require('./_stream_transform'); + var util = require('util'); + util.inherits(PassThrough, Transform); + +diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js +index 0c3fe3e..90a8298 100644 +--- a/lib/_stream_readable.js ++++ b/lib/_stream_readable.js +@@ -23,10 +23,34 @@ module.exports = Readable; + Readable.ReadableState = ReadableState; + + var EE = require('events').EventEmitter; ++if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { ++ return emitter.listeners(type).length; ++}; ++ ++if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { ++ return setTimeout(fn, 0); ++}; ++if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { ++ return clearTimeout(i); ++}; ++ + var Stream = require('stream'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var StringDecoder; +-var debug = util.debuglog('stream'); ++var debug; ++if (util.debuglog) ++ debug = util.debuglog('stream'); ++else try { ++ debug = require('debuglog')('stream'); ++} catch (er) { ++ debug = function() {}; ++} + + util.inherits(Readable, Stream); + +@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) { + + + function onEofChunk(stream, state) { +- if (state.decoder && !state.ended) { ++ if (state.decoder && !state.ended && state.decoder.end) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); +diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js +index b1f9fcc..b0caf57 100644 +--- a/lib/_stream_transform.js ++++ b/lib/_stream_transform.js +@@ -64,8 +64,14 @@ + + module.exports = Transform; + +-var Duplex = require('_stream_duplex'); ++var Duplex = require('./_stream_duplex'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + util.inherits(Transform, Duplex); + + +diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js +index ba2e920..f49288b 100644 +--- a/lib/_stream_writable.js ++++ b/lib/_stream_writable.js +@@ -27,6 +27,12 @@ module.exports = Writable; + Writable.WritableState = WritableState; + + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var Stream = require('stream'); + + util.inherits(Writable, Stream); +@@ -119,7 +125,7 @@ function WritableState(options, stream) { + function Writable(options) { + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. +- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) ++ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) + return new Writable(options); + + this._writableState = new WritableState(options, this); +diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js +index e3787e4..8cd2127 100644 +--- a/test/simple/test-stream-big-push.js ++++ b/test/simple/test-stream-big-push.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var str = 'asdfasdfasdfasdfasdf'; + + var r = new stream.Readable({ +diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js +index bb73777..d40efc7 100644 +--- a/test/simple/test-stream-end-paused.js ++++ b/test/simple/test-stream-end-paused.js +@@ -25,7 +25,7 @@ var gotEnd = false; + + // Make sure we don't miss the end event for paused 0-length streams + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var stream = new Readable(); + var calledRead = false; + stream._read = function() { +diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js +index b46ee90..0be8366 100644 +--- a/test/simple/test-stream-pipe-after-end.js ++++ b/test/simple/test-stream-pipe-after-end.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var util = require('util'); + + util.inherits(TestReadable, Readable); +diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js +deleted file mode 100644 +index f689358..0000000 +--- a/test/simple/test-stream-pipe-cleanup.js ++++ /dev/null +@@ -1,122 +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. +- +-// This test asserts that Stream.prototype.pipe does not leave listeners +-// hanging on the source or dest. +- +-var common = require('../common'); +-var stream = require('stream'); +-var assert = require('assert'); +-var util = require('util'); +- +-function Writable() { +- this.writable = true; +- this.endCalls = 0; +- stream.Stream.call(this); +-} +-util.inherits(Writable, stream.Stream); +-Writable.prototype.end = function() { +- this.endCalls++; +-}; +- +-Writable.prototype.destroy = function() { +- this.endCalls++; +-}; +- +-function Readable() { +- this.readable = true; +- stream.Stream.call(this); +-} +-util.inherits(Readable, stream.Stream); +- +-function Duplex() { +- this.readable = true; +- Writable.call(this); +-} +-util.inherits(Duplex, Writable); +- +-var i = 0; +-var limit = 100; +- +-var w = new Writable(); +- +-var r; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('end'); +-} +-assert.equal(0, r.listeners('end').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('close'); +-} +-assert.equal(0, r.listeners('close').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-r = new Readable(); +- +-for (i = 0; i < limit; i++) { +- w = new Writable(); +- r.pipe(w); +- w.emit('close'); +-} +-assert.equal(0, w.listeners('close').length); +- +-r = new Readable(); +-w = new Writable(); +-var d = new Duplex(); +-r.pipe(d); // pipeline A +-d.pipe(w); // pipeline B +-assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup +-assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-r.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 0); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-d.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 1); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 0); +-assert.equal(d.listeners('close').length, 0); +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 0); +diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js +index c5d724b..c7d6b7d 100644 +--- a/test/simple/test-stream-pipe-error-handling.js ++++ b/test/simple/test-stream-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Stream = require('stream').Stream; ++var Stream = require('../../').Stream; + + (function testErrorListenerCatches() { + var source = new Stream(); +diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js +index cb9d5fe..56f8d61 100644 +--- a/test/simple/test-stream-pipe-event.js ++++ b/test/simple/test-stream-pipe-event.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common'); +-var stream = require('stream'); ++var stream = require('../../'); + var assert = require('assert'); + var util = require('util'); + +diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js +index f2e6ec2..a5c9bf9 100644 +--- a/test/simple/test-stream-push-order.js ++++ b/test/simple/test-stream-push-order.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var assert = require('assert'); + + var s = new Readable({ +diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js +index 06f43dc..1701a9a 100644 +--- a/test/simple/test-stream-push-strings.js ++++ b/test/simple/test-stream-push-strings.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var util = require('util'); + + util.inherits(MyStream, Readable); +diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js +index ba6a577..a8e6f7b 100644 +--- a/test/simple/test-stream-readable-event.js ++++ b/test/simple/test-stream-readable-event.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + (function first() { + // First test, not reading when the readable is added. +diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js +index 2891ad6..11689ba 100644 +--- a/test/simple/test-stream-readable-flow-recursion.js ++++ b/test/simple/test-stream-readable-flow-recursion.js +@@ -27,7 +27,7 @@ var assert = require('assert'); + // more data continuously, but without triggering a nextTick + // warning or RangeError. + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + // throw an error if we trigger a nextTick warning. + process.throwDeprecation = true; +diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js +index 0c96476..7827538 100644 +--- a/test/simple/test-stream-unshift-empty-chunk.js ++++ b/test/simple/test-stream-unshift-empty-chunk.js +@@ -24,7 +24,7 @@ var assert = require('assert'); + + // This test verifies that stream.unshift(Buffer(0)) or + // stream.unshift('') does not set state.reading=false. +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + var r = new Readable(); + var nChunks = 10; +diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js +index 83fd9fa..17c18aa 100644 +--- a/test/simple/test-stream-unshift-read-race.js ++++ b/test/simple/test-stream-unshift-read-race.js +@@ -29,7 +29,7 @@ var assert = require('assert'); + // 3. push() after the EOF signaling null is an error. + // 4. _read() is not called after pushing the EOF null chunk. + +-var stream = require('stream'); ++var stream = require('../../'); + var hwm = 10; + var r = stream.Readable({ highWaterMark: hwm }); + var chunks = 10; +@@ -51,7 +51,14 @@ r._read = function(n) { + + function push(fast) { + assert(!pushedNull, 'push() after null push'); +- var c = pos >= data.length ? null : data.slice(pos, pos + n); ++ var c; ++ if (pos >= data.length) ++ c = null; ++ else { ++ if (n + pos > data.length) ++ n = data.length - pos; ++ c = data.slice(pos, pos + n); ++ } + pushedNull = c === null; + if (fast) { + pos += n; +diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js +index 5b49e6e..b5321f3 100644 +--- a/test/simple/test-stream-writev.js ++++ b/test/simple/test-stream-writev.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + + var queue = []; + for (var decode = 0; decode < 2; decode++) { +diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js +index 3814bf0..248c1be 100644 +--- a/test/simple/test-stream2-basic.js ++++ b/test/simple/test-stream2-basic.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js +index 6cdd4e9..f0fa84b 100644 +--- a/test/simple/test-stream2-compatibility.js ++++ b/test/simple/test-stream2-compatibility.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js +index 39b274f..006a19b 100644 +--- a/test/simple/test-stream2-finish-pipe.js ++++ b/test/simple/test-stream2-finish-pipe.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Buffer = require('buffer').Buffer; + + var r = new stream.Readable(); +diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js +deleted file mode 100644 +index e162406..0000000 +--- a/test/simple/test-stream2-fs.js ++++ /dev/null +@@ -1,72 +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 common = require('../common.js'); +-var R = require('_stream_readable'); +-var assert = require('assert'); +- +-var fs = require('fs'); +-var FSReadable = fs.ReadStream; +- +-var path = require('path'); +-var file = path.resolve(common.fixturesDir, 'x1024.txt'); +- +-var size = fs.statSync(file).size; +- +-var expectLengths = [1024]; +- +-var util = require('util'); +-var Stream = require('stream'); +- +-util.inherits(TestWriter, Stream); +- +-function TestWriter() { +- Stream.apply(this); +- this.buffer = []; +- this.length = 0; +-} +- +-TestWriter.prototype.write = function(c) { +- this.buffer.push(c.toString()); +- this.length += c.length; +- return true; +-}; +- +-TestWriter.prototype.end = function(c) { +- if (c) this.buffer.push(c.toString()); +- this.emit('results', this.buffer); +-} +- +-var r = new FSReadable(file); +-var w = new TestWriter(); +- +-w.on('results', function(res) { +- console.error(res, w.length); +- assert.equal(w.length, size); +- var l = 0; +- assert.deepEqual(res.map(function (c) { +- return c.length; +- }), expectLengths); +- console.log('ok'); +-}); +- +-r.pipe(w); +diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js +deleted file mode 100644 +index 15cffc2..0000000 +--- a/test/simple/test-stream2-httpclient-response-end.js ++++ /dev/null +@@ -1,52 +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 common = require('../common.js'); +-var assert = require('assert'); +-var http = require('http'); +-var msg = 'Hello'; +-var readable_event = false; +-var end_event = false; +-var server = http.createServer(function(req, res) { +- res.writeHead(200, {'Content-Type': 'text/plain'}); +- res.end(msg); +-}).listen(common.PORT, function() { +- http.get({port: common.PORT}, function(res) { +- var data = ''; +- res.on('readable', function() { +- console.log('readable event'); +- readable_event = true; +- data += res.read(); +- }); +- res.on('end', function() { +- console.log('end event'); +- end_event = true; +- assert.strictEqual(msg, data); +- server.close(); +- }); +- }); +-}); +- +-process.on('exit', function() { +- assert(readable_event); +- assert(end_event); +-}); +- +diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js +index 2fbfbca..667985b 100644 +--- a/test/simple/test-stream2-large-read-stall.js ++++ b/test/simple/test-stream2-large-read-stall.js +@@ -30,7 +30,7 @@ var PUSHSIZE = 20; + var PUSHCOUNT = 1000; + var HWM = 50; + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable({ + highWaterMark: HWM + }); +@@ -39,23 +39,23 @@ var rs = r._readableState; + r._read = push; + + r.on('readable', function() { +- console.error('>> readable'); ++ //console.error('>> readable'); + do { +- console.error(' > read(%d)', READSIZE); ++ //console.error(' > read(%d)', READSIZE); + var ret = r.read(READSIZE); +- console.error(' < %j (%d remain)', ret && ret.length, rs.length); ++ //console.error(' < %j (%d remain)', ret && ret.length, rs.length); + } while (ret && ret.length === READSIZE); + +- console.error('<< after read()', +- ret && ret.length, +- rs.needReadable, +- rs.length); ++ //console.error('<< after read()', ++ // ret && ret.length, ++ // rs.needReadable, ++ // rs.length); + }); + + var endEmitted = false; + r.on('end', function() { + endEmitted = true; +- console.error('end'); ++ //console.error('end'); + }); + + var pushes = 0; +@@ -64,11 +64,11 @@ function push() { + return; + + if (pushes++ === PUSHCOUNT) { +- console.error(' push(EOF)'); ++ //console.error(' push(EOF)'); + return r.push(null); + } + +- console.error(' push #%d', pushes); ++ //console.error(' push #%d', pushes); + if (r.push(new Buffer(PUSHSIZE))) + setTimeout(push); + } +diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js +index 3e6931d..ff47d89 100644 +--- a/test/simple/test-stream2-objects.js ++++ b/test/simple/test-stream2-objects.js +@@ -21,8 +21,8 @@ + + + var common = require('../common.js'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var assert = require('assert'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js +index cf7531c..e3f3e4e 100644 +--- a/test/simple/test-stream2-pipe-error-handling.js ++++ b/test/simple/test-stream2-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + (function testErrorListenerCatches() { + var count = 1000; +diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js +index 5e8e3cb..53b2616 100755 +--- a/test/simple/test-stream2-pipe-error-once-listener.js ++++ b/test/simple/test-stream2-pipe-error-once-listener.js +@@ -24,7 +24,7 @@ var common = require('../common.js'); + var assert = require('assert'); + + var util = require('util'); +-var stream = require('stream'); ++var stream = require('../../'); + + + var Read = function() { +diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js +index b63edc3..eb2b0e9 100644 +--- a/test/simple/test-stream2-push.js ++++ b/test/simple/test-stream2-push.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + var assert = require('assert'); +diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js +index e8a7305..9740a47 100644 +--- a/test/simple/test-stream2-read-sync-stack.js ++++ b/test/simple/test-stream2-read-sync-stack.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable(); + var N = 256 * 1024; + +diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +index cd30178..4b1659d 100644 +--- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js ++++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +@@ -22,10 +22,9 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + test1(); +-test2(); + + function test1() { + var r = new Readable(); +@@ -88,31 +87,3 @@ function test1() { + console.log('ok'); + }); + } +- +-function test2() { +- var r = new Readable({ encoding: 'base64' }); +- var reads = 5; +- r._read = function(n) { +- if (!reads--) +- return r.push(null); // EOF +- else +- return r.push(new Buffer('x')); +- }; +- +- var results = []; +- function flow() { +- var chunk; +- while (null !== (chunk = r.read())) +- results.push(chunk + ''); +- } +- r.on('readable', flow); +- r.on('end', function() { +- results.push('EOF'); +- }); +- flow(); +- +- process.on('exit', function() { +- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); +- console.log('ok'); +- }); +-} +diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js +index 7c96ffe..04a96f5 100644 +--- a/test/simple/test-stream2-readable-from-list.js ++++ b/test/simple/test-stream2-readable-from-list.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var fromList = require('_stream_readable')._fromList; ++var fromList = require('../../lib/_stream_readable')._fromList; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js +index 675da8e..51fd3d5 100644 +--- a/test/simple/test-stream2-readable-legacy-drain.js ++++ b/test/simple/test-stream2-readable-legacy-drain.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Stream = require('stream'); ++var Stream = require('../../'); + var Readable = Stream.Readable; + + var r = new Readable(); +diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js +index 7314ae7..c971898 100644 +--- a/test/simple/test-stream2-readable-non-empty-end.js ++++ b/test/simple/test-stream2-readable-non-empty-end.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + + var len = 0; + var chunks = new Array(10); +diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js +index 2e5cf25..fd8a3dc 100644 +--- a/test/simple/test-stream2-readable-wrap-empty.js ++++ b/test/simple/test-stream2-readable-wrap-empty.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + var EE = require('events').EventEmitter; + + var oldStream = new EE(); +diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js +index 90eea01..6b177f7 100644 +--- a/test/simple/test-stream2-readable-wrap.js ++++ b/test/simple/test-stream2-readable-wrap.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var EE = require('events').EventEmitter; + + var testRuns = 0, completedRuns = 0; +diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js +index 5d2c32a..685531b 100644 +--- a/test/simple/test-stream2-set-encoding.js ++++ b/test/simple/test-stream2-set-encoding.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var util = require('util'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js +index 9c9ddd8..a0cacc6 100644 +--- a/test/simple/test-stream2-transform.js ++++ b/test/simple/test-stream2-transform.js +@@ -21,8 +21,8 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var PassThrough = require('_stream_passthrough'); +-var Transform = require('_stream_transform'); ++var PassThrough = require('../../').PassThrough; ++var Transform = require('../../').Transform; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js +index d66dc3c..365b327 100644 +--- a/test/simple/test-stream2-unpipe-drain.js ++++ b/test/simple/test-stream2-unpipe-drain.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var crypto = require('crypto'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js +index 99f8746..17c92ae 100644 +--- a/test/simple/test-stream2-unpipe-leak.js ++++ b/test/simple/test-stream2-unpipe-leak.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + var chunk = new Buffer('hallo'); + +diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js +index 704100c..209c3a6 100644 +--- a/test/simple/test-stream2-writable.js ++++ b/test/simple/test-stream2-writable.js +@@ -20,8 +20,8 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var W = require('_stream_writable'); +-var D = require('_stream_duplex'); ++var W = require('../../').Writable; ++var D = require('../../').Duplex; + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js +index b91bde3..2f72c15 100644 +--- a/test/simple/test-stream3-pause-then-read.js ++++ b/test/simple/test-stream3-pause-then-read.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + 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..b513d61 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// 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/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// 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 passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; 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..19ab358 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,951 @@ +// 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; + + +/**/ +var debug = require('util'); +if (debug && debug.debuglog) { + debug = debug.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + var Duplex = require('./_stream_duplex'); + + 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; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + 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 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; + + // 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; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.readableObjectMode; + + // 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) { + var Duplex = require('./_stream_duplex'); + + 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 (util.isString(chunk) && !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 (util.isNullOrUndefined(chunk)) { + 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); + + if (!addToFront) + state.reading = false; + + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } 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); + } + } 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; + return this; +}; + +// 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 (isNaN(n) || util.isNull(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) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (!util.isNumber(n) || 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)) { + 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); + } + + 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 (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (util.isNull(ret)) { + 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 tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) + endReadable(this); + + if (!util.isNull(ret)) + this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !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; + + // emit 'readable' now to make sure it gets picked up. + 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; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + 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(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !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 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; + 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 : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + 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); + + 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', cleanup); + src.removeListener('data', ondata); + + // 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); + if (false === ret) { + debug('false write response, pause', + src._readableState.awaitDrain); + src._readableState.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 (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() { + 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() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) + state.awaitDrain--; + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + + +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; + 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; + 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 listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + var self = this; + process.nextTick(function() { + debug('readable nexttick read 0'); + self.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() { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + if (!state.reading) { + debug('resume read 0'); + this.read(0); + } + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(function() { + resume_(stream, state); + }); + } +} + +function resume_(stream, state) { + 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 (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } +} + +// 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() { + debug('wrapped end'); + 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) { + debug('wrapped data'); + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !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 (util.isFunction(stream[i]) && util.isUndefined(this[i])) { + 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) { + debug('wrapped _read', 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.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/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..905c5e4 --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,209 @@ +// 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 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 +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// 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'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (!util.isNullOrUndefined(data)) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('prefinish', function() { + if (util.isFunction(this._flush)) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// 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._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); + } +}; + +// 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) { + var ts = this._transformState; + + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + 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'); + + return stream.push(null); +} 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..db8539c --- /dev/null +++ b/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,477 @@ +// 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) { + var Duplex = require('./_stream_duplex'); + + 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; + var defaultHwm = options.objectMode ? 16 : 16 * 1024; + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) + this.objectMode = this.objectMode || !!options.writableObjectMode; + + // 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; + + // 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.buffer = []; + + // 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; +} + +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 (!util.isBuffer(chunk) && + !util.isString(chunk) && + !util.isNullOrUndefined(chunk) && + !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 (util.isFunction(encoding)) { + cb = encoding; + encoding = null; + } + + if (util.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (!util.isFunction(cb)) + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function() { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function() { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && + !state.corked && + !state.finished && + !state.bufferProcessing && + state.buffer.length) + clearBuffer(this, state); + } +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + util.isString(chunk)) { + 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 (util.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.corked) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + 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 (writev) + stream._writev(chunk, state.onwrite); + else + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + state.pendingcb--; + cb(er); + }); + else { + state.pendingcb--; + 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.corked && + !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); + 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; + + if (stream._writev && state.buffer.length > 1) { + // Fast case, write everything using _writev() + var cbs = []; + for (var c = 0; c < state.buffer.length; c++) + cbs.push(state.buffer[c].callback); + + // count the one we are adding, as well. + // TODO(isaacs) clean this up + state.pendingcb++; + doWrite(stream, state, true, state.length, state.buffer, '', function(err) { + for (var i = 0; i < cbs.length; i++) { + state.pendingcb--; + cbs[i](err); + } + }); + + // Clear buffer + state.buffer = []; + } else { + // Slow case, write chunks one-by-one + 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, false, 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; + } + } + + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; + } + + state.bufferProcessing = false; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); + +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (util.isFunction(chunk)) { + cb = chunk; + chunk = null; + encoding = null; + } else if (util.isFunction(encoding)) { + cb = encoding; + encoding = null; + } + + if (!util.isNullOrUndefined(chunk)) + this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // 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 prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else + prefinish(stream, state); + } + 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/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..a192a0f --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,65 @@ +{ + "_from": "readable-stream@1.x >=1.1.9", + "_id": "readable-stream@1.1.14", + "_inBundle": false, + "_integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "_location": "/readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "readable-stream@1.x >=1.1.9", + "name": "readable-stream", + "escapedName": "readable-stream", + "rawSpec": "1.x >=1.1.9", + "saveSpec": null, + "fetchSpec": "1.x >=1.1.9" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "_shasum": "7cf4c54ef648e3813084c636dd2079e166c081d9", + "_spec": "readable-stream@1.x >=1.1.9", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "browser": { + "util": false + }, + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + }, + "deprecated": false, + "description": "Streams3, a user-land copy of the stream library from Node.js v0.11.x", + "devDependencies": { + "tap": "~0.2.6" + }, + "homepage": "https://github.com/isaacs/readable-stream#readme", + "keywords": [ + "readable", + "stream", + "pipe" + ], + "license": "MIT", + "main": "readable.js", + "name": "readable-stream", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "version": "1.1.14" +} diff --git a/node_modules/readable-stream/passthrough.js b/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..2a8b5c6 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,10 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = require('stream'); +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'); +if (!process.browser && process.env.READABLE_STREAM === 'disable') { + module.exports = require('stream'); +} diff --git a/node_modules/readable-stream/transform.js b/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/readable-stream/writable.js b/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/requires-port/.npmignore b/node_modules/requires-port/.npmignore new file mode 100644 index 0000000..ba2a97b --- /dev/null +++ b/node_modules/requires-port/.npmignore @@ -0,0 +1,2 @@ +node_modules +coverage diff --git a/node_modules/requires-port/.travis.yml b/node_modules/requires-port/.travis.yml new file mode 100644 index 0000000..0765106 --- /dev/null +++ b/node_modules/requires-port/.travis.yml @@ -0,0 +1,19 @@ +sudo: false +language: node_js +node_js: + - "4" + - "iojs" + - "0.12" + - "0.10" +script: + - "npm run test-travis" +after_script: + - "npm install coveralls@2 && cat coverage/lcov.info | coveralls" +matrix: + fast_finish: true +notifications: + irc: + channels: + - "irc.freenode.org#unshift" + on_success: change + on_failure: change diff --git a/node_modules/requires-port/LICENSE b/node_modules/requires-port/LICENSE new file mode 100644 index 0000000..6dc9316 --- /dev/null +++ b/node_modules/requires-port/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the 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/requires-port/README.md b/node_modules/requires-port/README.md new file mode 100644 index 0000000..3effe75 --- /dev/null +++ b/node_modules/requires-port/README.md @@ -0,0 +1,47 @@ +# requires-port + +[![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](http://img.shields.io/npm/v/requires-port.svg?style=flat-square)](http://browsenpm.org/package/requires-port)[![Build Status](http://img.shields.io/travis/unshiftio/requires-port/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/requires-port)[![Dependencies](https://img.shields.io/david/unshiftio/requires-port.svg?style=flat-square)](https://david-dm.org/unshiftio/requires-port)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/requires-port/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/requires-port?branch=master)[![IRC channel](http://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](http://webchat.freenode.net/?channels=unshift) + +The module name says it all, check if a protocol requires a given port. + +## Installation + +This module is intended to be used with browserify or Node.js and is distributed +in the public npm registry. To install it simply run the following command from +your CLI: + +```j +npm install --save requires-port +``` + +## Usage + +The module exports it self as function and requires 2 arguments: + +1. The port number, can be a string or number. +2. Protocol, can be `http`, `http:` or even `https://yomoma.com`. We just split + it at `:` and use the first result. We currently accept the following + protocols: + - `http` + - `https` + - `ws` + - `wss` + - `ftp` + - `gopher` + - `file` + +It returns a boolean that indicates if protocol requires this port to be added +to your URL. + +```js +'use strict'; + +var required = require('requires-port'); + +console.log(required('8080', 'http')) // true +console.log(required('80', 'http')) // false +``` + +# License + +MIT diff --git a/node_modules/requires-port/index.js b/node_modules/requires-port/index.js new file mode 100644 index 0000000..4f267b2 --- /dev/null +++ b/node_modules/requires-port/index.js @@ -0,0 +1,38 @@ +'use strict'; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; diff --git a/node_modules/requires-port/package.json b/node_modules/requires-port/package.json new file mode 100644 index 0000000..0eabc93 --- /dev/null +++ b/node_modules/requires-port/package.json @@ -0,0 +1,74 @@ +{ + "_from": "requires-port@^1.0.0", + "_id": "requires-port@1.0.0", + "_inBundle": false, + "_integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "_location": "/requires-port", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "requires-port@^1.0.0", + "name": "requires-port", + "escapedName": "requires-port", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/url-parse" + ], + "_resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "_shasum": "925d2601d39ac485e091cf0da5c6e694dc3dcaff", + "_spec": "requires-port@^1.0.0", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\url-parse", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/unshiftio/requires-port/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Check if a protocol requires a certain port number to be added to an URL.", + "devDependencies": { + "assume": "1.3.x", + "istanbul": "0.4.x", + "mocha": "2.3.x", + "pre-commit": "1.1.x" + }, + "homepage": "https://github.com/unshiftio/requires-port", + "keywords": [ + "port", + "require", + "http", + "https", + "ws", + "wss", + "gopher", + "file", + "ftp", + "requires", + "requried", + "portnumber", + "url", + "parsing", + "validation", + "cows" + ], + "license": "MIT", + "main": "index.js", + "name": "requires-port", + "repository": { + "type": "git", + "url": "git+https://github.com/unshiftio/requires-port.git" + }, + "scripts": { + "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", + "coverage": "istanbul cover _mocha -- test.js", + "test": "mocha test.js", + "test-travis": "istanbul cover _mocha --report lcovonly -- test.js", + "watch": "mocha --watch test.js" + }, + "version": "1.0.0" +} diff --git a/node_modules/requires-port/test.js b/node_modules/requires-port/test.js new file mode 100644 index 0000000..93a0c74 --- /dev/null +++ b/node_modules/requires-port/test.js @@ -0,0 +1,98 @@ +describe('requires-port', function () { + 'use strict'; + + var assume = require('assume') + , required = require('./'); + + it('is exported as a function', function () { + assume(required).is.a('function'); + }); + + it('does not require empty ports', function () { + assume(required('', 'http')).false(); + assume(required('', 'wss')).false(); + assume(required('', 'ws')).false(); + assume(required('', 'cowsack')).false(); + }); + + it('assumes true for unknown protocols',function () { + assume(required('808', 'foo')).true(); + assume(required('80', 'bar')).true(); + }); + + it('never requires port numbers for file', function () { + assume(required(8080, 'file')).false(); + }); + + it('does not require port 80 for http', function () { + assume(required('80', 'http')).false(); + assume(required(80, 'http')).false(); + assume(required(80, 'http://')).false(); + assume(required(80, 'http://www.google.com')).false(); + + assume(required('8080', 'http')).true(); + assume(required(8080, 'http')).true(); + assume(required(8080, 'http://')).true(); + assume(required(8080, 'http://www.google.com')).true(); + }); + + it('does not require port 80 for ws', function () { + assume(required('80', 'ws')).false(); + assume(required(80, 'ws')).false(); + assume(required(80, 'ws://')).false(); + assume(required(80, 'ws://www.google.com')).false(); + + assume(required('8080', 'ws')).true(); + assume(required(8080, 'ws')).true(); + assume(required(8080, 'ws://')).true(); + assume(required(8080, 'ws://www.google.com')).true(); + }); + + it('does not require port 443 for https', function () { + assume(required('443', 'https')).false(); + assume(required(443, 'https')).false(); + assume(required(443, 'https://')).false(); + assume(required(443, 'https://www.google.com')).false(); + + assume(required('8080', 'https')).true(); + assume(required(8080, 'https')).true(); + assume(required(8080, 'https://')).true(); + assume(required(8080, 'https://www.google.com')).true(); + }); + + it('does not require port 443 for wss', function () { + assume(required('443', 'wss')).false(); + assume(required(443, 'wss')).false(); + assume(required(443, 'wss://')).false(); + assume(required(443, 'wss://www.google.com')).false(); + + assume(required('8080', 'wss')).true(); + assume(required(8080, 'wss')).true(); + assume(required(8080, 'wss://')).true(); + assume(required(8080, 'wss://www.google.com')).true(); + }); + + it('does not require port 21 for ftp', function () { + assume(required('21', 'ftp')).false(); + assume(required(21, 'ftp')).false(); + assume(required(21, 'ftp://')).false(); + assume(required(21, 'ftp://www.google.com')).false(); + + assume(required('8080', 'ftp')).true(); + assume(required(8080, 'ftp')).true(); + assume(required(8080, 'ftp://')).true(); + assume(required(8080, 'ftp://www.google.com')).true(); + }); + + it('does not require port 70 for gopher', function () { + assume(required('70', 'gopher')).false(); + assume(required(70, 'gopher')).false(); + assume(required(70, 'gopher://')).false(); + assume(required(70, 'gopher://www.google.com')).false(); + + assume(required('8080', 'gopher')).true(); + assume(required(8080, 'gopher')).true(); + assume(required(8080, 'gopher://')).true(); + assume(required(8080, 'gopher://www.google.com')).true(); + }); +}); diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +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 +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/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..f8d3ec9 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,65 @@ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* 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) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// 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..9c96819 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,76 @@ +{ + "_from": "safe-buffer@~5.2.1", + "_id": "safe-buffer@5.2.1", + "_inBundle": false, + "_integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@~5.2.1", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "~5.2.1", + "saveSpec": null, + "fetchSpec": "~5.2.1" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "_shasum": "1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6", + "_spec": "safe-buffer@~5.2.1", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^5.0.0" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "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.2.1" +} diff --git a/node_modules/string_decoder/.npmignore b/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +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/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**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/string_decoder/index.js b/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// 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/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..f577f58 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,53 @@ +{ + "_from": "string_decoder@~0.10.x", + "_id": "string_decoder@0.10.31", + "_inBundle": false, + "_integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "_location": "/string_decoder", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string_decoder@~0.10.x", + "name": "string_decoder", + "escapedName": "string_decoder", + "rawSpec": "~0.10.x", + "saveSpec": null, + "fetchSpec": "~0.10.x" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_spec": "string_decoder@~0.10.x", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\readable-stream", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "The string_decoder module from Node core", + "devDependencies": { + "tap": "~0.4.8" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "main": "index.js", + "name": "string_decoder", + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "version": "0.10.31" +} diff --git a/node_modules/url-parse/LICENSE b/node_modules/url-parse/LICENSE new file mode 100644 index 0000000..6dc9316 --- /dev/null +++ b/node_modules/url-parse/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the 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/url-parse/README.md b/node_modules/url-parse/README.md new file mode 100644 index 0000000..4540e4b --- /dev/null +++ b/node_modules/url-parse/README.md @@ -0,0 +1,147 @@ +# url-parse + +[![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](https://img.shields.io/npm/v/url-parse.svg?style=flat-square)](https://www.npmjs.com/package/url-parse)[![Build Status](https://img.shields.io/github/workflow/status/unshiftio/url-parse/CI/master?label=CI&style=flat-square)](https://github.com/unshiftio/url-parse/actions?query=workflow%3ACI+branch%3Amaster)[![Dependencies](https://img.shields.io/david/unshiftio/url-parse.svg?style=flat-square)](https://david-dm.org/unshiftio/url-parse)[![Coverage Status](https://img.shields.io/coveralls/unshiftio/url-parse/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/url-parse?branch=master)[![IRC channel](https://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](https://webchat.freenode.net/?channels=unshift) + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/url-parse.svg)](https://saucelabs.com/u/url-parse) + +The `url-parse` method exposes two different API interfaces. The +[`url`](https://nodejs.org/api/url.html) interface that you know from Node.js +and the new [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) +interface that is available in the latest browsers. + +In version `0.1` we moved from a DOM based parsing solution, using the `` +element, to a full Regular Expression solution. The main reason for this was +to make the URL parser available in different JavaScript environments as you +don't always have access to the DOM. An example of such environment is the +[`Worker`](https://developer.mozilla.org/en/docs/Web/API/Worker) interface. +The RegExp based solution didn't work well as it required a lot of lookups +causing major problems in FireFox. In version `1.0.0` we ditched the RegExp +based solution in favor of a pure string parsing solution which chops up the +URL into smaller pieces. This module still has a really small footprint as it +has been designed to be used on the client side. + +In addition to URL parsing we also expose the bundled `querystringify` module. + +## Installation + +This module is designed to be used using either browserify or Node.js it's +released in the public npm registry and can be installed using: + +``` +npm install url-parse +``` + +## Usage + +All examples assume that this library is bootstrapped using: + +```js +'use strict'; + +var Url = require('url-parse'); +``` + +To parse an URL simply call the `URL` method with the URL that needs to be +transformed into an object. + +```js +var url = new Url('https://github.com/foo/bar'); +``` + +The `new` keyword is optional but it will save you an extra function invocation. +The constructor takes the following arguments: + +- `url` (`String`): A string representing an absolute or relative URL. +- `baseURL` (`Object` | `String`): An object or string representing + the base URL to use in case `url` is a relative URL. This argument is + optional and defaults to [`location`](https://developer.mozilla.org/en-US/docs/Web/API/Location) + in the browser. +- `parser` (`Boolean` | `Function`): This argument is optional and specifies + how to parse the query string. By default it is `false` so the query string + is not parsed. If you pass `true` the query string is parsed using the + embedded `querystringify` module. If you pass a function the query string + will be parsed using this function. + +As said above we also support the Node.js interface so you can also use the +library in this way: + +```js +'use strict'; + +var parse = require('url-parse') + , url = parse('https://github.com/foo/bar', true); +``` + +The returned `url` instance contains the following properties: + +- `protocol`: The protocol scheme of the URL (e.g. `http:`). +- `slashes`: A boolean which indicates whether the `protocol` is followed by two + forward slashes (`//`). +- `auth`: Authentication information portion (e.g. `username:password`). +- `username`: Username of basic authentication. +- `password`: Password of basic authentication. +- `host`: Host name with port number. +- `hostname`: Host name without port number. +- `port`: Optional port number. +- `pathname`: URL path. +- `query`: Parsed object containing query string, unless parsing is set to false. +- `hash`: The "fragment" portion of the URL including the pound-sign (`#`). +- `href`: The full URL. +- `origin`: The origin of the URL. + +Note that when `url-parse` is used in a browser environment, it will default to +using the browser's current window location as the base URL when parsing all +inputs. To parse an input independently of the browser's current URL (e.g. for +functionality parity with the library in a Node environment), pass an empty +location object as the second parameter: + +```js +var parse = require('url-parse'); +parse('hostname', {}); +``` + +### Url.set(key, value) + +A simple helper function to change parts of the URL and propagating it through +all properties. When you set a new `host` you want the same value to be applied +to `port` if has a different port number, `hostname` so it has a correct name +again and `href` so you have a complete URL. + +```js +var parsed = parse('http://google.com/parse-things'); + +parsed.set('hostname', 'yahoo.com'); +console.log(parsed.href); // http://yahoo.com/parse-things +``` + +It's aware of default ports so you cannot set a port 80 on an URL which has +`http` as protocol. + +### Url.toString() + +The returned `url` object comes with a custom `toString` method which will +generate a full URL again when called. The method accepts an extra function +which will stringify the query string for you. If you don't supply a function we +will use our default method. + +```js +var location = url.toString(); // http://example.com/whatever/?qs=32 +``` + +You would rarely need to use this method as the full URL is also available as +`href` property. If you are using the `URL.set` method to make changes, this +will automatically update. + +## Testing + +The testing of this module is done in 3 different ways: + +1. We have unit tests that run under Node.js. You can run these tests with the + `npm test` command. +2. Code coverage can be run manually using `npm run coverage`. +3. For browser testing we use Sauce Labs and `zuul`. You can run browser tests + using the `npm run test-browser` command. + +## License + +[MIT](LICENSE) diff --git a/node_modules/url-parse/dist/url-parse.js b/node_modules/url-parse/dist/url-parse.js new file mode 100644 index 0000000..fd59e6e --- /dev/null +++ b/node_modules/url-parse/dist/url-parse.js @@ -0,0 +1,692 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.URLParse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= 2) { + rest = rest.slice(2); + } + } else if (isSpecial(protocol)) { + rest = match[4]; + } else if (protocol) { + if (forwardSlashes) { + rest = rest.slice(2); + } + } else if (slashesCount >= 2 && isSpecial(location.protocol)) { + rest = match[4]; + } + + return { + protocol: protocol, + slashes: forwardSlashes || isSpecial(protocol), + slashesCount: slashesCount, + rest: rest + }; +} + +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @private + */ +function resolve(relative, base) { + if (relative === '') return base; + + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; + + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } + + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); + + return path.join('/'); +} + +/** + * The actual URL instance. Instead of returning an object we've opted-in to + * create an actual constructor as it's much more memory efficient and + * faster and it pleases my OCD. + * + * It is worth noting that we should not use `URL` as class name to prevent + * clashes with the global URL instance that got introduced in browsers. + * + * @constructor + * @param {String} address URL we want to parse. + * @param {Object|String} [location] Location defaults for relative paths. + * @param {Boolean|Function} [parser] Parser for the query string. + * @private + */ +function Url(address, location, parser) { + address = trimLeft(address); + + if (!(this instanceof Url)) { + return new Url(address, location, parser); + } + + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() + , type = typeof location + , url = this + , i = 0; + + // + // The following if statements allows this module two have compatibility with + // 2 different API: + // + // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments + // where the boolean indicates that the query string should also be parsed. + // + // 2. The `URL` interface of the browser which accepts a URL, object as + // arguments. The supplied object will be used as default values / fall-back + // for relative paths. + // + if ('object' !== type && 'string' !== type) { + parser = location; + location = null; + } + + if (parser && 'function' !== typeof parser) parser = qs.parse; + + location = lolcation(location); + + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || '', location); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; + url.protocol = extracted.protocol || location.protocol || ''; + address = extracted.rest; + + // + // When the authority component is absent the URL starts with a path + // component. + // + if ( + extracted.protocol === 'file:' && ( + extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || + (!extracted.slashes && + (extracted.protocol || + extracted.slashesCount < 2 || + !isSpecial(url.protocol))) + ) { + instructions[3] = [/(.*)/, 'pathname']; + } + + for (; i < instructions.length; i++) { + instruction = instructions[i]; + + if (typeof instruction === 'function') { + address = instruction(address, url); + continue; + } + + parse = instruction[0]; + key = instruction[1]; + + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + if (~(index = address.indexOf(parse))) { + if ('number' === typeof instruction[2]) { + url[key] = address.slice(0, index); + address = address.slice(index + instruction[2]); + } else { + url[key] = address.slice(index); + address = address.slice(0, index); + } + } + } else if ((index = parse.exec(address))) { + url[key] = index[1]; + address = address.slice(0, index.index); + } + + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); + + // + // Hostname, host and protocol should be lowercased so they can be used to + // create a proper `origin`. + // + if (instruction[4]) url[key] = url[key].toLowerCase(); + } + + // + // Also parse the supplied query string in to an object. If we're supplied + // with a custom parser as function use that instead of the default build-in + // parser. + // + if (parser) url.query = parser(url.query); + + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } + + // + // Default to a / for pathname if none exists. This normalizes the URL + // to always have a / + // + if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) { + url.pathname = '/' + url.pathname; + } + + // + // We should not add port numbers if they are already the default port number + // for a given protocol. As the host also contains the port number we're going + // override it with the hostname which contains no port number. + // + if (!required(url.port, url.protocol)) { + url.host = url.hostname; + url.port = ''; + } + + // + // Parse down the `auth` for the username and password. + // + url.username = url.password = ''; + if (url.auth) { + instruction = url.auth.split(':'); + url.username = instruction[0] || ''; + url.password = instruction[1] || ''; + } + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + // + // The href is just the compiled result. + // + url.href = url.toString(); +} + +/** + * This is convenience method for changing properties in the URL instance to + * insure that they all propagate correctly. + * + * @param {String} part Property we need to adjust. + * @param {Mixed} value The newly assigned value. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. + * @returns {URL} URL instance for chaining. + * @public + */ +function set(part, value, fn) { + var url = this; + + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } + + url[part] = value; + break; + + case 'port': + url[part] = value; + + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } + + break; + + case 'hostname': + url[part] = value; + + if (url.port) value += ':'+ url.port; + url.host = value; + break; + + case 'host': + url[part] = value; + + if (/:\d+$/.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } + + break; + + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; + + case 'pathname': + case 'hash': + if (value) { + var char = part === 'pathname' ? '/' : '#'; + url[part] = value.charAt(0) !== char ? char + value : value; + } else { + url[part] = value; + } + break; + + default: + url[part] = value; + } + + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + url.href = url.toString(); + + return url; +} + +/** + * Transform the properties back in to a valid and full URL string. + * + * @param {Function} stringify Optional query stringify function. + * @returns {String} Compiled version of the URL. + * @public + */ +function toString(stringify) { + if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; + + var query + , url = this + , protocol = url.protocol; + + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; + + var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : ''); + + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } + + result += url.host + url.pathname; + + query = 'object' === typeof url.query ? stringify(url.query) : url.query; + if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + + if (url.hash) result += url.hash; + + return result; +} + +Url.prototype = { set: set, toString: toString }; + +// +// Expose the URL parser and some additional properties that might be useful for +// others or testing. +// +Url.extractProtocol = extractProtocol; +Url.location = lolcation; +Url.trimLeft = trimLeft; +Url.qs = qs; + +module.exports = Url; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"querystringify":2,"requires-port":3}],2:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , undef; + +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String|Null} The decoded string. + * @api private + */ +function decode(input) { + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} + +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } +} + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?#&]+)=?([^&]*)/g + , result = {} + , part; + + while (part = parser.exec(query)) { + var key = decode(part[1]) + , value = decode(part[2]); + + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; + result[key] = value; + } + + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + + var pairs = [] + , value + , key; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + + for (key in obj) { + if (has.call(obj, key)) { + value = obj[key]; + + // + // Edge cases where we actually want to encode the value to an empty + // string instead of the stringified value. + // + if (!value && (value === null || value === undef || isNaN(value))) { + value = ''; + } + + key = encode(key); + value = encode(value); + + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key +'='+ value); + } + } + + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; + +},{}],3:[function(require,module,exports){ +'use strict'; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +},{}]},{},[1])(1) +}); diff --git a/node_modules/url-parse/dist/url-parse.min.js b/node_modules/url-parse/dist/url-parse.min.js new file mode 100644 index 0000000..691a55b --- /dev/null +++ b/node_modules/url-parse/dist/url-parse.min.js @@ -0,0 +1 @@ +!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).URLParse=e()}(function(){return function r(n,s,a){function i(t,e){if(!s[t]){if(!n[t]){var o="function"==typeof require&&require;if(!e&&o)return o(t,!0);if(u)return u(t,!0);throw(o=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",o}o=s[t]={exports:{}},n[t][0].call(o.exports,function(e){return i(n[t][1][e]||e)},o,o.exports,r,n,s,a)}return s[t].exports}for(var u="function"==typeof require&&require,e=0;e= 2) { + rest = rest.slice(2); + } + } else if (isSpecial(protocol)) { + rest = match[4]; + } else if (protocol) { + if (forwardSlashes) { + rest = rest.slice(2); + } + } else if (slashesCount >= 2 && isSpecial(location.protocol)) { + rest = match[4]; + } + + return { + protocol: protocol, + slashes: forwardSlashes || isSpecial(protocol), + slashesCount: slashesCount, + rest: rest + }; +} + +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @private + */ +function resolve(relative, base) { + if (relative === '') return base; + + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; + + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } + + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); + + return path.join('/'); +} + +/** + * The actual URL instance. Instead of returning an object we've opted-in to + * create an actual constructor as it's much more memory efficient and + * faster and it pleases my OCD. + * + * It is worth noting that we should not use `URL` as class name to prevent + * clashes with the global URL instance that got introduced in browsers. + * + * @constructor + * @param {String} address URL we want to parse. + * @param {Object|String} [location] Location defaults for relative paths. + * @param {Boolean|Function} [parser] Parser for the query string. + * @private + */ +function Url(address, location, parser) { + address = trimLeft(address); + + if (!(this instanceof Url)) { + return new Url(address, location, parser); + } + + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() + , type = typeof location + , url = this + , i = 0; + + // + // The following if statements allows this module two have compatibility with + // 2 different API: + // + // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments + // where the boolean indicates that the query string should also be parsed. + // + // 2. The `URL` interface of the browser which accepts a URL, object as + // arguments. The supplied object will be used as default values / fall-back + // for relative paths. + // + if ('object' !== type && 'string' !== type) { + parser = location; + location = null; + } + + if (parser && 'function' !== typeof parser) parser = qs.parse; + + location = lolcation(location); + + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || '', location); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; + url.protocol = extracted.protocol || location.protocol || ''; + address = extracted.rest; + + // + // When the authority component is absent the URL starts with a path + // component. + // + if ( + extracted.protocol === 'file:' && ( + extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || + (!extracted.slashes && + (extracted.protocol || + extracted.slashesCount < 2 || + !isSpecial(url.protocol))) + ) { + instructions[3] = [/(.*)/, 'pathname']; + } + + for (; i < instructions.length; i++) { + instruction = instructions[i]; + + if (typeof instruction === 'function') { + address = instruction(address, url); + continue; + } + + parse = instruction[0]; + key = instruction[1]; + + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + if (~(index = address.indexOf(parse))) { + if ('number' === typeof instruction[2]) { + url[key] = address.slice(0, index); + address = address.slice(index + instruction[2]); + } else { + url[key] = address.slice(index); + address = address.slice(0, index); + } + } + } else if ((index = parse.exec(address))) { + url[key] = index[1]; + address = address.slice(0, index.index); + } + + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); + + // + // Hostname, host and protocol should be lowercased so they can be used to + // create a proper `origin`. + // + if (instruction[4]) url[key] = url[key].toLowerCase(); + } + + // + // Also parse the supplied query string in to an object. If we're supplied + // with a custom parser as function use that instead of the default build-in + // parser. + // + if (parser) url.query = parser(url.query); + + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } + + // + // Default to a / for pathname if none exists. This normalizes the URL + // to always have a / + // + if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) { + url.pathname = '/' + url.pathname; + } + + // + // We should not add port numbers if they are already the default port number + // for a given protocol. As the host also contains the port number we're going + // override it with the hostname which contains no port number. + // + if (!required(url.port, url.protocol)) { + url.host = url.hostname; + url.port = ''; + } + + // + // Parse down the `auth` for the username and password. + // + url.username = url.password = ''; + if (url.auth) { + instruction = url.auth.split(':'); + url.username = instruction[0] || ''; + url.password = instruction[1] || ''; + } + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + // + // The href is just the compiled result. + // + url.href = url.toString(); +} + +/** + * This is convenience method for changing properties in the URL instance to + * insure that they all propagate correctly. + * + * @param {String} part Property we need to adjust. + * @param {Mixed} value The newly assigned value. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. + * @returns {URL} URL instance for chaining. + * @public + */ +function set(part, value, fn) { + var url = this; + + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } + + url[part] = value; + break; + + case 'port': + url[part] = value; + + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } + + break; + + case 'hostname': + url[part] = value; + + if (url.port) value += ':'+ url.port; + url.host = value; + break; + + case 'host': + url[part] = value; + + if (/:\d+$/.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } + + break; + + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; + + case 'pathname': + case 'hash': + if (value) { + var char = part === 'pathname' ? '/' : '#'; + url[part] = value.charAt(0) !== char ? char + value : value; + } else { + url[part] = value; + } + break; + + default: + url[part] = value; + } + + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + url.href = url.toString(); + + return url; +} + +/** + * Transform the properties back in to a valid and full URL string. + * + * @param {Function} stringify Optional query stringify function. + * @returns {String} Compiled version of the URL. + * @public + */ +function toString(stringify) { + if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; + + var query + , url = this + , protocol = url.protocol; + + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; + + var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : ''); + + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } + + result += url.host + url.pathname; + + query = 'object' === typeof url.query ? stringify(url.query) : url.query; + if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + + if (url.hash) result += url.hash; + + return result; +} + +Url.prototype = { set: set, toString: toString }; + +// +// Expose the URL parser and some additional properties that might be useful for +// others or testing. +// +Url.extractProtocol = extractProtocol; +Url.location = lolcation; +Url.trimLeft = trimLeft; +Url.qs = qs; + +module.exports = Url; diff --git a/node_modules/url-parse/package.json b/node_modules/url-parse/package.json new file mode 100644 index 0000000..aae333e --- /dev/null +++ b/node_modules/url-parse/package.json @@ -0,0 +1,80 @@ +{ + "_from": "url-parse@~1.5.1", + "_id": "url-parse@1.5.3", + "_inBundle": false, + "_integrity": "sha512-IIORyIQD9rvj0A4CLWsHkBBJuNqWpFQe224b6j9t/ABmquIS0qDU2pY6kl6AuOrL5OkCXHMCFNe1jBcuAggjvQ==", + "_location": "/url-parse", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "url-parse@~1.5.1", + "name": "url-parse", + "escapedName": "url-parse", + "rawSpec": "~1.5.1", + "saveSpec": null, + "fetchSpec": "~1.5.1" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.3.tgz", + "_shasum": "71c1303d38fb6639ade183c2992c8cc0686df862", + "_spec": "url-parse@~1.5.1", + "_where": "C:\\Users\\shake\\Desktop\\projects\\node\\rabbitmq\\node_modules\\amqplib", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/unshiftio/url-parse/issues" + }, + "bundleDependencies": false, + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + }, + "deprecated": false, + "description": "Small footprint URL parser that works seamlessly across Node.js and browser environments", + "devDependencies": { + "assume": "^2.2.0", + "browserify": "^17.0.0", + "c8": "^7.3.1", + "mocha": "^8.0.1", + "pre-commit": "^1.2.2", + "sauce-browsers": "^2.0.0", + "sauce-test": "^1.3.3", + "uglify-js": "^3.5.7" + }, + "files": [ + "index.js", + "dist" + ], + "homepage": "https://github.com/unshiftio/url-parse#readme", + "keywords": [ + "URL", + "parser", + "uri", + "url", + "parse", + "query", + "string", + "querystring", + "stringify" + ], + "license": "MIT", + "main": "index.js", + "name": "url-parse", + "repository": { + "type": "git", + "url": "git+https://github.com/unshiftio/url-parse.git" + }, + "scripts": { + "browserify": "rm -rf dist && mkdir -p dist && browserify index.js -s URLParse -o dist/url-parse.js", + "minify": "uglifyjs dist/url-parse.js --source-map -cm -o dist/url-parse.min.js", + "prepublishOnly": "npm run browserify && npm run minify", + "test": "c8 --reporter=lcov --reporter=text mocha test/test.js", + "test-browser": "node test/browser.js", + "watch": "mocha --watch test/test.js" + }, + "version": "1.5.3" +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..049448a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,116 @@ +{ + "name": "rabbitmq", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "amqplib": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.8.0.tgz", + "integrity": "sha512-icU+a4kkq4Y1PS4NNi+YPDMwdlbFcZ1EZTQT2nigW3fvOb6AOgUQ9+Mk4ue0Zu5cBg/XpDzB40oH10ysrk2dmA==", + "requires": { + "bitsyntax": "~0.1.0", + "bluebird": "^3.7.2", + "buffer-more-ints": "~1.0.0", + "readable-stream": "1.x >=1.1.9", + "safe-buffer": "~5.2.1", + "url-parse": "~1.5.1" + } + }, + "bitsyntax": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.1.0.tgz", + "integrity": "sha512-ikAdCnrloKmFOugAfxWws89/fPc+nw0OOG1IzIE72uSOg/A3cYptKCjSUhDTuj7fhsJtzkzlv7l3b8PzRHLN0Q==", + "requires": { + "buffer-more-ints": "~1.0.0", + "debug": "~2.6.9", + "safe-buffer": "~5.1.2" + }, + "dependencies": { + "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==" + } + } + }, + "bluebird": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz", + "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==" + }, + "buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==" + }, + "core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==" + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + }, + "url-parse": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.3.tgz", + "integrity": "sha512-IIORyIQD9rvj0A4CLWsHkBBJuNqWpFQe224b6j9t/ABmquIS0qDU2pY6kl6AuOrL5OkCXHMCFNe1jBcuAggjvQ==", + "requires": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..abe621e --- /dev/null +++ b/package.json @@ -0,0 +1,15 @@ +{ + "name": "rabbitmq", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "amqplib": "^0.8.0" + } +} diff --git a/publisher.js b/publisher.js new file mode 100644 index 0000000..223b19d --- /dev/null +++ b/publisher.js @@ -0,0 +1,27 @@ +// Use the advanced messaging queue protocol +const amqp = require('amqplib'); + +// Dummy message to be sent +const msg = { jobNumber: 13 }; + +connect(); + +// Create connection to server +async function connect() { + try { + const connection = await amqp.connect('amqp://localhost:5672'); + + // Create channel + const channel = await connection.createChannel(); + + // Create queue + const result = await channel.assertQueue('jobs'); + + // Send message + channel.sendToQueue('jobs', Bufferl.from(JSON.stringify(msg))); + + console.log(`job ${msq.jobNumber} has been sent successfully`); + } catch (ex) { + console.error(ex); + } +}